473,668 Members | 2,632 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Tkinter event error

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:

Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2. class spreadsheet(Frame):
  3.     """
  4.     initialize columns and rows, default of 5
  5.     """
  6.     def __init__(self, parent=None, numrow=5, numcol=5):
  7.         Frame.__init__(self, parent)
  8.         self.numrow = numrow
  9.         self.numcol = numcol
  10.         self.makeWidgets(numrow, numcol)
  11.  
  12.     def onEvent(self, event, cell):
  13.         """ define events, evaluate and show cell
  14.         """
  15.         if event.num == 1:
  16.             print cell  # this should actually replace what is in the cell without losing original data
  17.         if event.num == 3:
  18.             obj = dict[cell]   #error here, says cell is unscriptable.
  19.             data = obj.get()
  20.             if data.startwith('='):
  21.                 eq = data.lstrip('=')
  22.                 print data, eq
  23.                 try:
  24.                     result = eval(eq)
  25.                     obj.delete(0, 'end')
  26.                     obj.insert(0, str(result))
  27.                 except:
  28.                     pass  #nothing should crash the spreadsheet
  29.  
  30.     def returnKey(event, cell):
  31.         pass
  32.  
  33.     def makeWidgets(self, numrow, numcol):
  34.         """
  35.         define labels for rows and columns, use entry widget, assign events, create dictionary of
  36.         cell:widget pair
  37.         """
  38.         dict = {}
  39.         w = 20
  40.         h = 1
  41.         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']
  42.         for row in range(numrow):
  43.             for col in range(numcol):
  44.                 if col == 0:
  45.                     # label rows
  46.                     labels = Label(root, width = 3, text = rowLabel[row])
  47.                     labels.grid(row=row, column=col, padx = 2, pady = 2)
  48.                 elif row == 0:
  49.                     # label columns
  50.                     labels = Label(root, width=3, text = str(col-1))
  51.                     labels.grid(row=row, column=col, padx = 2, pady =2)
  52.                 else:
  53.                     # use entry widget
  54.                     entrys = Entry(root, width=w)
  55.                     entrys.grid(row=row, column=col)
  56.                     cell = "%s%s" %(rowLabel[col], row)
  57.                     dict[cell] = entrys
  58.                     # bind to left mouse click
  59.                     entrys.bind('<Button-1>', lambda e, cell=cell: self.onEvent(e, cell))
  60.                     # bind the object to a right mouse click
  61.                     entrys.bind('<Button-3>', lambda e, cell=cell: self.onEvent(e, cell))
  62.                     # bind the object to a return/enter press
  63.                     entrys.bind('<Return>', lambda e, cell=cell: self.returnKey(e, cell))
  64.         # start curser in row a column 0
  65.         dict['a1'].focus()
  66. if __name__ == '__main__':
  67.     import sys
  68.     root = Tk()
  69.     root.title('S P R E A D S H E E T')
  70.     if len(sys.argv) != 3:
  71.         spreadsheet(root).grid()
  72.     else:
  73.         rows, cols = eval(sys.argv[1]), eval(sys.argv[2])
  74.         spreadsheet(root, rows, cols).grid()
  75.     root.mainloop()
  76.  
  77.  
  78.  
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
Mar 27 '07 #1
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.
Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2. class spreadsheet(Frame):
  3.     """
  4.     initialize columns and rows, default of 5
  5.     """
  6.     def __init__(self, parent=None, numrow=5, numcol=5):
  7.         Frame.__init__(self, parent)
  8.         self.numrow = numrow
  9.         self.numcol = numcol
  10.  
  11.         # Need to keep the entries dictionary in self
  12.         self.entriesDict = {}    # an empty dictionary
  13.         # Don't use the keyword "dict"; use somethingDict.
  14.  
  15.         self.makeWidgets(numrow, numcol)
  16.  
  17.     def onEvent(self, event, cell):
  18.         """ define events, evaluate and show cell
  19.         """
  20.         if event.num == 1:
  21.             print cell  # this should actually replace what is in the cell without losing original data
  22.         if event.num == 3:
  23.             obj = self.entriesDict[cell]   #error here, says cell is unscriptable.
  24.             data = obj.get()
  25.             if data.startswith('='):  # startswith() was startwith()
  26.                 eq = data.lstrip('=')
  27.                 print data, eq
  28.                 try:
  29.                     result = eval(eq)
  30.                     obj.delete(0, 'end')
  31.                     obj.insert(0, str(result))
  32.                 except:
  33.                     pass  #nothing should crash the spreadsheet
  34.  
  35.     def returnKey(self, event, cell):
  36.         pass
  37.  
  38.     def makeWidgets(self, numrow, numcol):
  39.         """
  40.         define labels for rows and columns, use entry widget, assign events, create dictionary of
  41.         cell:widget pair
  42.         """
  43.         dict = {}
  44.         w = 20
  45.         h = 1
  46.         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']
  47.         for row in range(numrow):
  48.             for col in range(numcol):
  49.                 if col == 0:
  50.                     # label rows
  51.                     labels = Label(root, width = 3, text = rowLabel[row])
  52.                     labels.grid(row=row, column=col, padx = 2, pady = 2)
  53.                 elif row == 0:
  54.                     # label columns
  55.                     labels = Label(root, width=3, text = str(col-1))
  56.                     labels.grid(row=row, column=col, padx = 2, pady =2)
  57.                 else:
  58.                     # use entry widget
  59.                     entrys = Entry(root, width=w)
  60.                     entrys.grid(row=row, column=col)
  61.                     cell = "%s%s" %(rowLabel[col], row)
  62.                     self.entriesDict[cell] = entrys
  63.                     # bind to left mouse click
  64.                     entrys.bind('<Button-1>', lambda e, cell=cell: self.onEvent(e, cell))
  65.                     # bind the object to a right mouse click
  66.                     entrys.bind('<Button-3>', lambda e, cell=cell: self.onEvent(e, cell))
  67.                     # bind the object to a return/enter press
  68.                     entrys.bind('<Return>', lambda e, cell=cell: self.returnKey(e, cell))
  69.         # start curser in row a column 0
  70.         self.entriesDict['a1'].focus()
  71. if __name__ == '__main__':
  72.     import sys
  73.     root = Tk()
  74.     root.title('S P R E A D S H E E T')
  75.     if len(sys.argv) != 3:
  76.         spreadsheet(root).grid()
  77.     else:
  78.         rows, cols = eval(sys.argv[1]), eval(sys.argv[2])
  79.         spreadsheet(root, rows, cols).grid()
  80.     root.mainloop()
  81.  
Mar 27 '07 #2
TMS
119 New Member
OF COURSE... thank you :) I should have caught that.

again... TYVM
tms
Mar 27 '07 #3
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!
Mar 27 '07 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

3
2423
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)
3
12540
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:
6
6082
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
0
1305
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...
2
5076
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")
8
8117
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
2
9570
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...
1
5106
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):
2
3957
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,...
1
2032
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:...
0
8367
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,...
1
8570
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,...
0
8650
tracyyun
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...
0
7391
agi2029
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...
1
6206
isladogs
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...
0
5677
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();...
1
2781
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
2
2017
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1779
bsmnconsultancy
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...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.