TMS 119
New Member
Only a few weeks of school left. This assignment and then a project to go (GASP).
I'm writing a spreadsheet. I am required to have each 'cell' do 2 things: Evaluate if it is an equation, or if its a string just print it. Also, it is supposed to print the cell number on a different event reuqest.
Right now, I'm trying to get it to evaluate an equation, and I'm real close. I'm getting errors in the onEvent() function. I know it has to do with a syntax issue and I'm hoping you can find it. Been looking at this since yesterday and I'm frustrated.
I'm trying lambda functions, and perhaps that is where the problem is, or its just something else that I've overlooked. Here is what I have: -
from Tkinter import *
-
class spreadsheet(Frame):
-
"""
-
initialize columns and rows, default of 5
-
"""
-
def __init__(self, parent=None, numrow=5, numcol=5):
-
Frame.__init__(self, parent)
-
self.numrow = numrow
-
self.numcol = numcol
-
self.makeWidgets(numrow, numcol)
-
-
def onEvent(self, event, cell):
-
""" define events, evaluate and show cell
-
"""
-
if event.num == 1:
-
print cell # this should actually replace what is in the cell without losing original data
-
if event.num == 3:
-
obj = dict[cell] #error here, says cell is unscriptable.
-
data = obj.get()
-
if data.startwith('='):
-
eq = data.lstrip('=')
-
print data, eq
-
try:
-
result = eval(eq)
-
obj.delete(0, 'end')
-
obj.insert(0, str(result))
-
except:
-
pass #nothing should crash the spreadsheet
-
-
def returnKey(event, cell):
-
pass
-
-
def makeWidgets(self, numrow, numcol):
-
"""
-
define labels for rows and columns, use entry widget, assign events, create dictionary of
-
cell:widget pair
-
"""
-
dict = {}
-
w = 20
-
h = 1
-
rowLabel = ["", 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
-
for row in range(numrow):
-
for col in range(numcol):
-
if col == 0:
-
# label rows
-
labels = Label(root, width = 3, text = rowLabel[row])
-
labels.grid(row=row, column=col, padx = 2, pady = 2)
-
elif row == 0:
-
# label columns
-
labels = Label(root, width=3, text = str(col-1))
-
labels.grid(row=row, column=col, padx = 2, pady =2)
-
else:
-
# use entry widget
-
entrys = Entry(root, width=w)
-
entrys.grid(row=row, column=col)
-
cell = "%s%s" %(rowLabel[col], row)
-
dict[cell] = entrys
-
# bind to left mouse click
-
entrys.bind('<Button-1>', lambda e, cell=cell: self.onEvent(e, cell))
-
# bind the object to a right mouse click
-
entrys.bind('<Button-3>', lambda e, cell=cell: self.onEvent(e, cell))
-
# bind the object to a return/enter press
-
entrys.bind('<Return>', lambda e, cell=cell: self.returnKey(e, cell))
-
# start curser in row a column 0
-
dict['a1'].focus()
-
if __name__ == '__main__':
-
import sys
-
root = Tk()
-
root.title('S P R E A D S H E E T')
-
if len(sys.argv) != 3:
-
spreadsheet(root).grid()
-
else:
-
rows, cols = eval(sys.argv[1]), eval(sys.argv[2])
-
spreadsheet(root, rows, cols).grid()
-
root.mainloop()
-
-
-
thank you ahead of time for your help. I look forward to learning this language AFTER the class is over, when I can go back to the stuff that I missed with the breakneck speeds we've been using since taking this class.
TMS
3 1660 bartonc 6,596
Recognized Expert Expert
Very nice job!!! Your trouble was with your use of dict. That dictionary needed to be an instance variable too. - from Tkinter import *
-
class spreadsheet(Frame):
-
"""
-
initialize columns and rows, default of 5
-
"""
-
def __init__(self, parent=None, numrow=5, numcol=5):
-
Frame.__init__(self, parent)
-
self.numrow = numrow
-
self.numcol = numcol
-
-
# Need to keep the entries dictionary in self
-
self.entriesDict = {} # an empty dictionary
-
# Don't use the keyword "dict"; use somethingDict.
-
-
self.makeWidgets(numrow, numcol)
-
-
def onEvent(self, event, cell):
-
""" define events, evaluate and show cell
-
"""
-
if event.num == 1:
-
print cell # this should actually replace what is in the cell without losing original data
-
if event.num == 3:
-
obj = self.entriesDict[cell] #error here, says cell is unscriptable.
-
data = obj.get()
-
if data.startswith('='): # startswith() was startwith()
-
eq = data.lstrip('=')
-
print data, eq
-
try:
-
result = eval(eq)
-
obj.delete(0, 'end')
-
obj.insert(0, str(result))
-
except:
-
pass #nothing should crash the spreadsheet
-
-
def returnKey(self, event, cell):
-
pass
-
-
def makeWidgets(self, numrow, numcol):
-
"""
-
define labels for rows and columns, use entry widget, assign events, create dictionary of
-
cell:widget pair
-
"""
-
dict = {}
-
w = 20
-
h = 1
-
rowLabel = ["", 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
-
for row in range(numrow):
-
for col in range(numcol):
-
if col == 0:
-
# label rows
-
labels = Label(root, width = 3, text = rowLabel[row])
-
labels.grid(row=row, column=col, padx = 2, pady = 2)
-
elif row == 0:
-
# label columns
-
labels = Label(root, width=3, text = str(col-1))
-
labels.grid(row=row, column=col, padx = 2, pady =2)
-
else:
-
# use entry widget
-
entrys = Entry(root, width=w)
-
entrys.grid(row=row, column=col)
-
cell = "%s%s" %(rowLabel[col], row)
-
self.entriesDict[cell] = entrys
-
# bind to left mouse click
-
entrys.bind('<Button-1>', lambda e, cell=cell: self.onEvent(e, cell))
-
# bind the object to a right mouse click
-
entrys.bind('<Button-3>', lambda e, cell=cell: self.onEvent(e, cell))
-
# bind the object to a return/enter press
-
entrys.bind('<Return>', lambda e, cell=cell: self.returnKey(e, cell))
-
# start curser in row a column 0
-
self.entriesDict['a1'].focus()
-
if __name__ == '__main__':
-
import sys
-
root = Tk()
-
root.title('S P R E A D S H E E T')
-
if len(sys.argv) != 3:
-
spreadsheet(root).grid()
-
else:
-
rows, cols = eval(sys.argv[1]), eval(sys.argv[2])
-
spreadsheet(root, rows, cols).grid()
-
root.mainloop()
-
TMS 119
New Member
OF COURSE... thank you :) I should have caught that.
again... TYVM
tms
bartonc 6,596
Recognized Expert Expert
OF COURSE... thank you :) I should have caught that.
again... TYVM
tms
You are welcome, very much. Any time!
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: Ivan Letal |
last post by:
I have just tried this code..
Tkinter import *
root = Tk()
def callback(event):
print "clicked at", event.x, event.y
frame = Frame(root, width=100, height=100)
|
by: Adonis |
last post by:
I wish to manually move widgets in Tkinter, now I have successfully done it,
but with odd results, I would like to move the widgets with a much smoother
manner, and better precision.
Any help is greatly appreciated.
--
here is snip of working code:
|
by: Elaine Jackson |
last post by:
I've got a script where a button gets pushed over and over: to cut down on the
carpal tunnel syndrome I'd like to have the button respond to presses of the
Enter key as well as mouse clicks; can somebody clue me in regarding how this is
done? Muchas gracias.
Peace
|
by: Bryan Olson |
last post by:
I've run into a problem with Python/TkInter crashing, with an
attempt to read illegal addresses, on Win on Win2000 and WinXP.
With some web-searching, I found that people say not to
manipulate TkInter from multiple threads, except that the call
event_generate() is safe. I assume the call adds an event to
Tk's queue, and later the thread running mainloop will() pick up
the event.
I tried to write a general-purpose thread-runner. In...
|
by: Grooooops |
last post by:
I've been hacking around this for a few days and have gotten close to
what I want... but not quite...
The TKinter Docs provide this example:
# configure text tag
text.tag_config("a", foreground="blue", underline=1)
text.tag_bind("a", "<Enter>", show_hand_cursor)
text.tag_bind("a", "<Leave>", show_arrow_cursor)
text.tag_bind("a", "<Button-1>", click)
text.config(cursor="arrow")
| |
by: Jay |
last post by:
I'm having a problem using lambda to use a command with an argument for
a button in Tkinter.
buttons = range(5)
for x in xrange(5):
buttons = Button(frame, text=str(x+1), command=lambda:
self.highlight(x))
buttons.pack(side=LEFT)
The buttons are correctly numbered 1 through 5, but no matter which
|
by: Kevin Walzer |
last post by:
I'm trying to decide whether I need threads in my Tkinter application or
not. My app is a front end to a command-line tool; it feeds commands to
the command-line program, then reads its output and displays it in a
Tkinter text widget. Some of the commands are long-running and/or return
thousands of lines of output.
I initially thought I needed to use threading, because the GUI would
block when reading the output, even when I configured...
|
by: vigacmoe |
last post by:
Hi all,
I'm trying to write a simple tkinter program, then this problem popped
up. The followin code will describe the problem.
------------------------------------------
import Tkinter
class countdown(Tkinter.Frame):
|
by: Kevin Walzer |
last post by:
I'm porting a Tkinter application to wxPython and had a question about
wxPython's event loop.
The Tkinter app provides a GUI to a command-line tool. It gathers user
input, and opens an asynchronous pipe to the external tool via
os.popen(). Then, it dumps the output from the external process into a
text display. Although threads are often recommended for use with GUI
apps, I am able to keep the GUI responsive with Tkinter's event loop,...
|
by: Noah |
last post by:
I'm trying to match against Event.type for KeyPress and ButtonPress.
Currently I'm using integer constants (2 and 4). Are these constants
defined anywhere? The docs talk about KeyPress and ButtonPress, but I
don't see them in any of the Tkinter source files. Are these just
magic values that come out of the TK side of things and are not
defined in Python? Code like this makes me think I'm doing something
wrong:
if event.type == 2:...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |