Re: python strings and {} in Tkinter entry widgets
On Aug 16, 2010, at 11:40 AM, Jeff Hobbs wrote: On Aug 15, 4:41 pm, Chris Hare ch...@labr.net wrote: I have some code that pulls a value from a database. In this case, it is three space delimited words. When I display the value in a Tkinter.Entry widget, the text has curly braces around it, even when there are none in the surrounding the text in the database. Is this normal, and how do I prevent it or remove them correctly before displaying the text in the Entry widget? Python ['', '', ''] == Tcl {{} {} {}} Python 'a word' == Tcl {a word} You are getting a literal translation occurring, and you need to split/ join or index the items properly. Without being more clear how you want to represent your data, what you need isn't clear. Perhaps you just need to reference the first index of the variable, or ... who knows, there are lots of possibilities. Jeff -- http://mail.python.org/mailman/listinfo/python-list Actually I want all of the words, as they form the name of an organization entered by the user. So the space delimited words should be displayed without the {} in the tkinker entry box. The contents of the widget is a persons first and last name, space delimited -- http://mail.python.org/mailman/listinfo/python-list
adding a windows item to a menu bar dynamically
I want to add a Windows menu item to my menu bar, so when another Toplevel window is opened, I can add that to the menu bar in case the user accidentally clicks on a different window and moves the Toplevel under something else. Then when the window is closed, remove the window from the menu Any ideas on how to do this? Thanks -- http://mail.python.org/mailman/listinfo/python-list
python strings and {} in Tkinter entry widgets
I have some code that pulls a value from a database. In this case, it is three space delimited words. When I display the value in a Tkinter.Entry widget, the text has curly braces around it, even when there are none in the surrounding the text in the database. Is this normal, and how do I prevent it or remove them correctly before displaying the text in the Entry widget? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Tk window and contents will not display
The scenario is this: I want to loop around all of the images in a given directory (which I know will be images, but I guess I should check), show an image in a window, wait 2 seconds and show the next one and repeat that indefinitley, which will be until the user closes the window. This is the code I extracted from the larger program and made work - sort of - in a standalone fashion. When I run the code, each of the file names gets displayed, and I can view the images, so it has to be something I am doing wrong with this chunk of code. However, I don't see what the problem is. from Tkinter import * import time import os import ImageTk import Image class externalLoopDisplay: def show(self): # # Create a frame # self.window = Tk() self.f = Frame(self.window, bg=Gray) self.f.grid() self.btnRefresh = Button(self.f, text=Close, command=self.window.destroy, bg=Gray,highlightbackground=Red, highlightcolor=Green) self.btnRefresh.grid(row=0, column=2) self.loopImage() def loopImage(self): dir = Radar/net17 while 1: fileList = os.listdir(dir) number = len(fileList) c = 1 for gifFile in fileList: print externalLoopDisplay.show:,top of for loop + str(c) + of + str(number) print externalLoopDisplay.show:,showing file + dir + / + gifFile self.window.title(Image + str(c) + of + str(number)) image = Image.open(dir + / + gifFile) canvasWidth, canvasHeight = image.size self.w = Canvas(self.f, width=canvasWidth, height=canvasHeight) photo = ImageTk.PhotoImage(image=image) netRadarImage = Label(self.w, image=photo) netRadarImage.image = photo self.w.grid(row=1, column=0, columnspan=3) netRadarImage.grid( row=1, column=0) time.sleep(10) c = c + 1 self.w.destroy() loop=externalLoopDisplay() loop.show() -- http://mail.python.org/mailman/listinfo/python-list
Re: Tk window and contents will not display
On Aug 14, 2010, at 3:14 PM, Peter Otten wrote: Chris Hare wrote: The scenario is this: I want to loop around all of the images in a given directory (which I know will be images, but I guess I should check), show an image in a window, wait 2 seconds and show the next one and repeat that indefinitley, which will be until the user closes the window. This is the code I extracted from the larger program and made work - sort of - in a standalone fashion. When I run the code, each of the file names gets displayed, and I can view the images, so it has to be something I am doing wrong with this chunk of code. However, I don't see what the problem is. I have not looked at your code in detail, but event loops and time.sleep() don't play together very well. Use after(delay_in_milliseconds, callable) instead. Here's a simple example that loops over images passed from the command line: import Image import ImageTk import os import sys import Tkinter as tk from itertools import cycle def next_image(): imagefile = next(imagefiles) image = Image.open(imagefile) w, h = image.size image = image.resize((700, 700*h//w)) label.image = label[image] = ImageTk.PhotoImage(image=image) root.title(Now showing %s % os.path.basename(imagefile)) root.after(2000, next_image) if __name__ == __main__: imagefiles = sys.argv[1:] assert imagefiles imagefiles = cycle(imagefiles) root = tk.Tk() label = tk.Label(root) label.pack() root.after_idle(next_image) root.mainloop() Thanks Peter. I threw away what I started with and merged your code into my class: class externalLoopDisplay: def show(self): main.logging.debug(externalLoopDisplay.show:,start) self.window = Tk() self.btnClose = Button(self.window, text=Close, command=self.window.destroy, bg=backColor,highlightbackground=warnColor, highlightcolor=okColor) self.btnClose.grid(row=0, column=2) self.label = Label(self.window) self.label.grid(row=1, column=0, columnspan=3) dirName = getRadarPath() + /net + str(netNumber.get()) # e.g. .../Radar/net17/net17-MMDDHHMMSS.gif self.imagefiles = glob.glob(dirName + /*.gif) self.imagefiles = cycle(self.imagefiles) self.window.after_idle(self.next_image) def next_image(self): imagefile = next(self.imagefiles) image = Image.open(imagefile) w, h = image.size image = image.resize((600, 550*h//w)) self.label.image = self.label[image] = ImageTk.PhotoImage(image=image) # bails here self.window.title(Now showing %s % os.path.basename(imagefile)) self.window.after(2000, next_image) I marked where the code bails with an error saying pyimage2 doesn't exist. All of the images exist and worked just fine with your standalone script. Suggestions? -- http://mail.python.org/mailman/listinfo/python-list
Re: Tk window and contents will not display
On Aug 14, 2010, at 5:49 PM, Peter Otten wrote: Chris Hare wrote: Thanks Peter. I threw away what I started with and merged your code into my class: class externalLoopDisplay: def show(self): main.logging.debug(externalLoopDisplay.show:,start) self.window = Tk() self.btnClose = Button(self.window, text=Close, command=self.window.destroy, bg=backColor,highlightbackground=warnColor, highlightcolor=okColor) self.btnClose.grid(row=0, column=2) self.label = Label(self.window) self.label.grid(row=1, column=0, columnspan=3) dirName = getRadarPath() + /net + str(netNumber.get()) # e.g. .../Radar/net17/net17-MMDDHHMMSS.gif self.imagefiles = glob.glob(dirName + /*.gif) self.imagefiles = cycle(self.imagefiles) self.window.after_idle(self.next_image) def next_image(self): imagefile = next(self.imagefiles) image = Image.open(imagefile) w, h = image.size image = image.resize((600, 550*h//w)) self.label.image = self.label[image] = ImageTk.PhotoImage(image=image) # bails here self.window.title(Now showing %s % os.path.basename(imagefile)) self.window.after(2000, next_image) I marked where the code bails with an error saying pyimage2 doesn't exist. All of the images exist and worked just fine with your standalone script. Suggestions? Google says you are calling Tkinter.Tk() more than once where you should instead use Tkinter.Toplevel(). As you didn't post that part of the code it's hard to verify, but when I add a second root = tk.Tk() to my example script I get a very similar exception: Exception in Tkinter callback Traceback (most recent call last): File /usr/lib/python2.6/lib-tk/Tkinter.py, line 1413, in __call__ return self.func(*args) File /usr/lib/python2.6/lib-tk/Tkinter.py, line 498, in callit func(*args) File cycle_image.py, line 16, in next_image label.image = label[image] = ImageTk.PhotoImage(image=image) File /usr/lib/python2.6/lib-tk/Tkinter.py, line 1212, in __setitem__ self.configure({key: value}) File /usr/lib/python2.6/lib-tk/Tkinter.py, line 1205, in configure return self._configure('configure', cnf, kw) File /usr/lib/python2.6/lib-tk/Tkinter.py, line 1196, in _configure self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) TclError: image pyimage1 doesn't exist By the way: for future posts please remember to cut and paste the traceback, don't paraphrase the error message. Peter -- http://mail.python.org/mailman/listinfo/python-list Yes - you are bang on. Thanks. One final question if I may, how would you suggest I handle checking for new files and adding them to the list? For example, if the loop is playing and a new image is added, how can I detect it and then refresh the list of file? I am stuck on that part with this new approach. Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Tk window and contents will not display
On Aug 14, 2010, at 6:46 PM, Peter Otten wrote: Chris Hare wrote: On Aug 14, 2010, at 5:49 PM, Peter Otten wrote: Chris Hare wrote: Thanks Peter. I threw away what I started with and merged your code into my class: class externalLoopDisplay: def show(self): main.logging.debug(externalLoopDisplay.show:,start) self.window = Tk() self.btnClose = Button(self.window, text=Close, command=self.window.destroy, bg=backColor,highlightbackground=warnColor, highlightcolor=okColor) self.btnClose.grid(row=0, column=2) self.label = Label(self.window) self.label.grid(row=1, column=0, columnspan=3) dirName = getRadarPath() + /net + str(netNumber.get()) # e.g. .../Radar/net17/net17-MMDDHHMMSS.gif Thanks. One final question if I may, how would you suggest I handle checking for new files and adding them to the list? For example, if the loop is playing and a new image is added, how can I detect it and then refresh the list of file? I am stuck on that part with this new approach. Chris Replacing self.imagefiles = glob.glob(dirName + /*.gif) self.imagefiles = cycle(self.imagefiles) with self.imagefiles = image_cycler(os.path.join(dirname, *.gif)) where image_cycler() looks as follows def image_cycler(pattern): while True: for fn in glob.glob(pattern): yield fn would be the simplest way. Peter -- http://mail.python.org/mailman/listinfo/python-list Perfect! Thank you -- http://mail.python.org/mailman/listinfo/python-list
Re: sched() function questions
On Aug 7, 2010, at 1:30 AM, Dennis Lee Bieber wrote: On Fri, 06 Aug 2010 22:37:26 -0500, Chris Hare ch...@labr.net declaimed the following in gmane.comp.python.general: print str(s.queue()) I don't find a queue method defined for scheduler objects in the documentation for my version of Python (2.5) What I am trying to do is mimic the Timer function, where my code will continue to function while my scheduled function executes in 15 minutes or 900 seconds. This doesn't do it though. Any help? And what IS it doing? On my system, I'd expect the program to fail when trying to print whatever that queue() method is supposed to return. However, here is the key item you seem to have missed -- from the documentation: -=-=-=-=- run( ) Run all scheduled events. This function will wait (using the delayfunc function passed to the constructor) for the next event, then execute it and so on until there are no more scheduled events. -=-=-=-=- As soon as you call s.run() the entire PROGRAM goes into a wait state until the first of the queued events time expires. AND won't return until ALL events have happened. To have scheduled events happen asynchronously you will have to instantiate a THREAD which runs the scheduler... Of course, for your simple example, who needs the scheduler -- a simple sleep() in the thread will do what you attempted... The scheduler is useful when you want to queue a whole bunch of timed events and have them run in order at the set times... maybe even have events add more events to the system. -- Wulfraed Dennis Lee Bieber AF6VN wlfr...@ix.netcom.comHTTP://wlfraed.home.netcom.com/ -- http://mail.python.org/mailman/listinfo/python-listThanks Dennis. I guess I will have to figure out how to resolve the sqlite error -- http://mail.python.org/mailman/listinfo/python-list
sched() function questions
I am currently using threading.timer to execute an event in my big chunk of code. This is causing a problem with sqlite, so I am trying to figure out the sched function import sched import time def timerfunc(): print hello, time.time() return(time.time()) def delay(period): time.sleep(period) def some(): s.enterabs(900,1, timerfunc, () ) s.run() s = sched.scheduler(timerfunc, delay) print time.time() some() x = 0 while 1: print x x = x + 1 time.sleep(60) print str(s.queue()) What I am trying to do is mimic the Timer function, where my code will continue to function while my scheduled function executes in 15 minutes or 900 seconds. This doesn't do it though. Any help? -- http://mail.python.org/mailman/listinfo/python-list
assigning variables from list data
I have a database query result (see code below). In PHP, I would have said list(var1,var2,var) = $result and each element in the list would be assigned to each of the named variables. I have my data coming out of the database, and I can see it is a list. so my question is, instead of having to do the variable assignment as I have it here, is there a way more like PHP or am I stuck with it? import sqlite3 as sqlite try: print connecting to disk db ... conn = sqlite.connect(netcomm.db) except: print oops print retrieving data cursor = conn.cursor() cursor.execute('select * from net where NetNumber 0') list = cursor.fetchone() print list print len(list) for item in list: print item netNumber = list[0] netType = list[1] netConditions = list[2] netStartLocal = list[3] NCS = list[4] NCS1 = list[5] RADAR = list[6] NetFreq = list[7] Repeater = list[8] Notes = list[9] -- http://mail.python.org/mailman/listinfo/python-list
defining, raising and catching exceptions
I have a block of test code, where I am trying to raise and catch my own user defined exception class NetActiveError(RuntimeError): def __init__(self,error): self.args = error def a(): try: fh = open(me.txt, r) except Exception as (errno, errText): print errText try: b() except NetActiveError as (errono, errText): print errno, errText def b(): print def b raise NetActiveError,net already running a() When I run it though, I get the following error: chare$ python z No such file or directory def b Traceback (most recent call last): File z, line 20, in module a() File z, line 12, in a except NetActiveError as (errono, errText): ValueError: too many values to unpack What am I doing wrong here? -- http://mail.python.org/mailman/listinfo/python-list
Re: defining, raising and catching exceptions
okay - but why does the response come back like No such file or directory def b ('n', 'e', 't', ' ', 'a', 'l', 'r', 'e', 'a', 'd', 'y', ' ', 'r', 'u', 'n', 'n', 'i', 'n', 'g') On Aug 5, 2010, at 5:49 PM, Benjamin Kaplan wrote: What makes you think it has to do with user-defined exceptions? try : ...raise Exception(hello) ... except Exception as (errno, errText) : ... print whatever ... Traceback (most recent call last): ValueError: need more than 1 values to unpack An Exception is an object, not a tuple of number and text. Raise an instance of the exception, not the class: raise NetActiveError(net already running) And then catch the exception object except NetActiveError as err: print err.args On Thu, Aug 5, 2010 at 3:41 PM, Chris Hare ch...@labr.net wrote: I have a block of test code, where I am trying to raise and catch my own user defined exception class NetActiveError(RuntimeError): def __init__(self,error): self.args = error def a(): try: fh = open(me.txt, r) except Exception as (errno, errText): print errText try: b() except NetActiveError as (errono, errText): print errno, errText def b(): print def b raise NetActiveError,net already running a() When I run it though, I get the following error: chare$ python z No such file or directory def b Traceback (most recent call last): File z, line 20, in module a() File z, line 12, in a except NetActiveError as (errono, errText): ValueError: too many values to unpack What am I doing wrong here? -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: defining, raising and catching exceptions
On Aug 5, 2010, at 7:37 PM, MRAB wrote: Chris Hare wrote: okay - but why does the response come back like No such file or directory def b ('n', 'e', 't', ' ', 'a', 'l', 'r', 'e', 'a', 'd', 'y', ' ', 'r', 'u', 'n', 'n', 'i', 'n', 'g') The class Exception saves its arguments in the 'args' instance attribute, and when it prints the exception it prints those arguments: e = Exception(1, 2, 3) print e.args (1, 2, 3) print e (1, 2, 3) print repr(e) Exception(1, 2, 3) NetActiveError inherits from RuntimeError, and ultimately from Exception. NetActiveError sets the 'args' attribute to its single string argument, and when the exception is printed out it thinks it's the arguments: e.args = string print e ('s', 't', 'r', 'i', 'n', 'g') print repr(e) Exception('s', 't', 'r', 'i', 'n', 'g') The correct way to create your own exceptions is to call the superclass's __init__ method: class NetActiveError(RuntimeError): ... def __init__(self, error): ... RuntimeError.__init__(self, error) ... e = NetActiveError(string) print e string print repr(e) NetActiveError('string',) On Aug 5, 2010, at 5:49 PM, Benjamin Kaplan wrote: What makes you think it has to do with user-defined exceptions? try : ...raise Exception(hello) ... except Exception as (errno, errText) : ... print whatever ... Traceback (most recent call last): ValueError: need more than 1 values to unpack An Exception is an object, not a tuple of number and text. Raise an instance of the exception, not the class: raise NetActiveError(net already running) And then catch the exception object except NetActiveError as err: print err.args On Thu, Aug 5, 2010 at 3:41 PM, Chris Hare ch...@labr.net wrote: I have a block of test code, where I am trying to raise and catch my own user defined exception class NetActiveError(RuntimeError): def __init__(self,error): self.args = error def a(): try: fh = open(me.txt, r) except Exception as (errno, errText): print errText try: b() except NetActiveError as (errono, errText): print errno, errText def b(): print def b raise NetActiveError,net already running a() When I run it though, I get the following error: chare$ python z No such file or directory def b Traceback (most recent call last): File z, line 20, in module a() File z, line 12, in a except NetActiveError as (errono, errText): ValueError: too many values to unpack What am I doing wrong here? -- http://mail.python.org/mailman/listinfo/python-list okay - thanks for the tutorial -- you explained what I couldn't find in the docs I looked at. I appreciate your help -- http://mail.python.org/mailman/listinfo/python-list
problem adding a scrollbar to a text widget
Here is my chunk of code. I can't figure out what I am doing wrong to put my scrollbar on the right hand side of the text box. from Tkinter import * def showLogFile(): top = Toplevel() f = Frame(top, bd=0, bg=Gray) top.title = netcomm log file f.grid() sc = Scrollbar(top) sc.grid() t = Text(f, yscrollcommand = sc.set) sc.config(command=t.yview) t.insert(END,This is a line of text) t.config(height=20,width=80,bg=Gray) button = Button(f, text=Dismiss, command=top.destroy, highlightbackground=Red) t.grid() button.grid() showLogFile() mainloop() -- http://mail.python.org/mailman/listinfo/python-list
running a piece of code at specific intervals?
Don't say cron : I want to have a section of my code executed at 15 minute intervals. I am using Threading.timer, but it is causing a problem sinxe I am using sqlite3 and the thread support gives me an error, which aborts part of my code. So, is there an alternative to threading.timer? -- http://mail.python.org/mailman/listinfo/python-list
adding optionMenu items in code
I have an option menu self.w = OptionMenu(self.frameNewNet, self.variable, one, two, three) Is there a way to add items to this programmatically, i.e. using values from a database? -- http://mail.python.org/mailman/listinfo/python-list
Re: calling a class method from a menu in a different class
No offense taken. I'll get getting the Google Python Style Guide today. I'll package up the code tonight and it to the group. Fortunately ( or unfortunately), it is all in one file right now. On Aug 2, 2010, at 10:31 PM, rantingrick wrote: Chris, It looks as if you are calling a class object and not an instance object. However i cannot be for sure because you are using improper Python style. All classes should be capwords. But here again you have used camelcase for the class identifiers radarWidgets and mainDisplay, which is bad bad bad!! You been asking multiple questions about this code for the last couple of days (and thats fine). However, maybe you would do everyone a favor by posting the entire code so we can offer suggestions. Just seeing seeing a snipit here and a snipit there is not helping because we don't know where else you may be screwing up that we cannot see. It seems you're committing many faux pas with not only your coding style but also your coding practices. I've seen overuse of globals and bad styles and on and on. So post the entire code so myself and others can go through this mess and get it sorted out. If you keep on with your bad habits you're never going to become proficient with Python. I am sorry if this post seems condescending because that is not the case. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: calling a class method from a menu in a different class
Oh and Risk, I know I was calling the class object. class 1 creates the instance object class 2 tries to use the instance object so the problem is how to make class 2 knowledgable of instance object? I guess I could pass the instance object into the class, since class1 creates the instance and also calls class 2. On Aug 2, 2010, at 10:31 PM, rantingrick wrote: Chris, It looks as if you are calling a class object and not an instance object. However i cannot be for sure because you are using improper Python style. All classes should be capwords. But here again you have used camelcase for the class identifiers radarWidgets and mainDisplay, which is bad bad bad!! You been asking multiple questions about this code for the last couple of days (and thats fine). However, maybe you would do everyone a favor by posting the entire code so we can offer suggestions. Just seeing seeing a snipit here and a snipit there is not helping because we don't know where else you may be screwing up that we cannot see. It seems you're committing many faux pas with not only your coding style but also your coding practices. I've seen overuse of globals and bad styles and on and on. So post the entire code so myself and others can go through this mess and get it sorted out. If you keep on with your bad habits you're never going to become proficient with Python. I am sorry if this post seems condescending because that is not the case. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner python GUI question
On Aug 1, 2010, at 8:33 PM, rechardchen wrote: δΊ 2010-8-2 6:15, Chris Hare ει: I hope I can explain this correctly. I have a GUI, which is already being processed by a mainloop. I want to be able to open a second window so the user can interact with specific information in the second window. I pulled together this code example from Tkinter import * class Net: def __init__(self,tkWin): self.window = tkWin def show(self,t): self.l = Label(self.window,text=t) self.l.grid() button = Button(self.window, text=Again) button.bind(Button-1, self.Again) button.grid() def Again(self,event): win3 = Tk() x = Net(win3) x.show(window 3) root = Tk() root.title = test f = Frame(root,bg=Yellow) l = Label(f,text=window 1) f.grid() l.grid() win2 = Tk() x = Net(win2) x.show(window 2) if __name__ == __main__: root.mainloop() Is this the right way to do things, or would you suggest something different? Thanks, Chris Using Tkinter.Toplevel may be better. :) -- http://mail.python.org/mailman/listinfo/python-list I thought that would be a good idea, so I changed the code a bit to this: from Tkinter import * class Net: def __init__(self): self.window = Toplevel() def show(self,t): self.l = Label(self.window,text=t) self.l.grid() button = Button(self.window, text=Again) button.bind(Button-1, self.Again) button2 = Button(self.window, text=Dismiss) button2.bind(Button-1, self.window.destroy) button.grid() button2.grid() def Again(self,event): x = Net() x.show(window 3) root = Tk() root.title = test f = Frame(root,bg=Yellow) l = Label(f,text=window 1) f.grid() l.grid() x = Net() x.show(window 2) if __name__ == __main__: root.mainloop() I put the call to Topevel into the Class. This however, gets me an error message Traceback (most recent call last): File a.py, line 27, in module x = Net() File a.py, line 5, in __init__ self.window = Toplevel() File /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py, line 1978, in __init__ self.title(root.title()) TypeError: 'str' object is not callable I should think it would work, but I don't understand why it doesn't. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: beginner python GUI question
On Aug 2, 2010, at 7:25 AM, Peter Otten wrote: Chris Hare wrote: root = Tk() root.title = test I should think it would work, but I don't understand why it doesn't. Try root.title(test) title() is a method that you are hiding with your attribute leading to problems later on. By the way, what kind of documentation are you using for your efforts? Here's a concise one: http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html Also, effbot.org has a lot of information that you best access via Google. Peter -- http://mail.python.org/mailman/listinfo/python-list I have several python books and I have been using effbot and various other sources. Thanks for the help. Your suggestion (and a couple others I added) got my example working exactly like I want it, so I can incorporate that into my program. Thanks again. Chris -- http://mail.python.org/mailman/listinfo/python-list
namespaces, scoping and variables
I am having a problem getting around this variable namespace thing. Consider these code bits File a.py from Tkinter import * import a1 def doAgain(): x = a1.Net() x.show(Again!) root = Tk() root.title(test) f = Frame(root,bg=Yellow) l = Button(root,text=window 1,command=doAgain) f.grid() l.grid() a = 5 x = a1.Net() x.show(window 2) if __name__ == __main__: root.mainloop() File a1.py from Tkinter import * class Net: def __init__(self): self.window = Toplevel() def show(self,t): self.l = Label(self.window,text=t) self.l.grid() button = Button(self.window, text=Again) button.bind(Button-1, self.Again) button2 = Button(self.window, text=Dismiss) button2.bind(Button-1, self.hide) button.grid() button2.grid() def Again(self,event): x = Net() x.show(a) def hide(self,event): self.window.destroy() When I run a.py, it imports a1.py and click on the Again button, I get the error Exception in Tkinter callback Traceback (most recent call last): File /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py, line 1410, in __call__ return self.func(*args) File /Volumes/Development/py/a1.py, line 17, in Again x.show(a) NameError: global name 'a' is not defined I believe this is the expected behavior. so my question is this -- how do I tell the code in a1.py about the variable a, which exists in a.py? Do I have to pass it as part of the function call, or what? using global a in a1.py doesn't change anything. since I am using SQLite for the disk database, I was thinking I could keep all the global variables in an in memory database and just access them when I need to, but other ideas are welcome. Thanks, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: namespaces, scoping and variables
Thanks to everyone for answering my question. I think its clear now. I'll just go the stuff 'em in a module and import that route. Chris On Aug 2, 2010, at 3:03 PM, MRAB wrote: Chris Hare wrote: I am having a problem getting around this variable namespace thing. Consider these code bits File a.py from Tkinter import * import a1 def doAgain(): x = a1.Net() x.show(Again!) root = Tk() root.title(test) f = Frame(root,bg=Yellow) l = Button(root,text=window 1,command=doAgain) f.grid() l.grid() a = 5 x = a1.Net() x.show(window 2) if __name__ == __main__: root.mainloop() File a1.py from Tkinter import * class Net: def __init__(self): self.window = Toplevel() def show(self,t): self.l = Label(self.window,text=t) self.l.grid() button = Button(self.window, text=Again) button.bind(Button-1, self.Again) button2 = Button(self.window, text=Dismiss) button2.bind(Button-1, self.hide) button.grid() button2.grid() def Again(self,event): x = Net() x.show(a) def hide(self,event): self.window.destroy() When I run a.py, it imports a1.py and click on the Again button, I get the error Exception in Tkinter callback Traceback (most recent call last): File /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py, line 1410, in __call__ return self.func(*args) File /Volumes/Development/py/a1.py, line 17, in Again x.show(a) NameError: global name 'a' is not defined I believe this is the expected behavior. so my question is this -- how do I tell the code in a1.py about the variable a, which exists in a.py? Do I have to pass it as part of the function call, or what? using global a in a1.py doesn't change anything. since I am using SQLite for the disk database, I was thinking I could keep all the global variables in an in memory database and just access them when I need to, but other ideas are welcome. Why in a database? If you need the modules to share it then you could put it in a shared module and refer to it there: File a.py - import my_globals ... my_globals.a = 5 File a1.py -- import my_globals ... x.show(my_globals.a) -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: how best to clear objects from a frame
On Aug 1, 2010, at 10:13 PM, rantingrick wrote: On Aug 1, 7:12 pm, Chris Hare ch...@labr.net wrote: Here is the situation: I have a window with a bunch of widgets in it. I want to clear the objects in a given frame and recreate them to update them. You need to check out the w.update and w.update_idletasks methods available on all Tkinter widgets. Just FYI: to remove a widget from view without destroying it use w.pack_forget or w.grid_forget. However if you are simply trying to refresh a widget use one of the update methods. -- http://mail.python.org/mailman/listinfo/python-list I will have a look at those. Consider a frame with a label and a button. How do I address the label to change it from another function in the class? -- http://mail.python.org/mailman/listinfo/python-list
calling a class method from a menu in a different class
What I am trying to do is call a class function from a menu, for example displaySubMenu.add_radiobutton(label=Medium, variable=radarPanelSize, command=radarWidgets.refresh) class radarWidgets: def __init__(self,root): self.window = root def refresh(self): global radar global refreshTimer self.refreshTimer.cancel() logging.debug(handlesRadarRefreshByTimer()) # # destroy the existing frame the radar is in # self.w.destroy() self.lblLastUpdate.destroy() self.btnRefresh.destroy() # # rebuild the radarWidgets # self.createImage() self.refreshTimer = threading.Timer( 900, self.refresh) self.refreshTimer.start() This doesn't work because the instance of radarWidgets was defined in a different class .. class mainDisplay: def __init__(self,root): self.window = root def show(self): # # Configure the base frame # base=Frame(self.window,bg=backColor,width=1200, height=800) base.grid() frameRadar = Frame(base, bd=0, bg=backColor) frameRadar.grid(row=2,column=1,sticky=N+E+S+W) # radar = radarWidgets(frameRadar) radar.show() so the actual instance is called radar. If I put the instance name in the menu item, I get an error that radar is unknown. If I use RadarWidgets.refresh ins the command for the menu, I get the error: TypeError: unbound method refresh() must be called with radarWidgets instance as first argument (got nothing instead) Any ideas? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
class doesn't open its window - newbie question
I am a newbie to python, but not programming. I have a menubar item displaySubMenu.add_command(label=External, command=externalDisplay) externalDisplay is a new class, which I have already imported. The class is here: from Tkinter import * from datetime import datetime, date, time import urllib from PIL import Image #import Image # PIL required import ImageTk backColor = Gray highcolor = Green entryColor = Cyan okColor = Green warnColor = Red class externalDisplay(Frame): def __init__(self,callSign,nexrad): Initialize yourself self.callSign = callSign self.nexrad = nexrad #Initialise the base class Frame.__init__(self) Set the Window Title #self.title( Test) self.findu = http://www.findu.com/cgi-bin/radar-find.cgi?call=; + self.callSign + radar= + self.nexrad Display the main window with a little bit of padding self.grid(padx=5,pady=5) self.CreateWidgets() def CreateWidgets(self): #Create all the widgets that we need self.f = Frame(self, bd=0, bg=backColor) self.title = netcomm Online Radar self.f.grid() # # Insert the date and time the radar image was updated # self.lblLastUpdate = Label(self.f, text=Last Updated: + str(datetime.now()), bg=backColor) self.lblLastUpdate.grid( row=0, column=0, sticky=W) self.btnRefresh = Button(self.f, text=Refresh, command=handlesExternalDisplayByClick, bg=backColor,highlightbackground=okColor,highlightcolor=highcolor) self.btnRefresh.grid(row=0, column=1) self.btnRefresh = Button(self.f, text=Close, command=self.destroy, bg=backColor,highlightbackground=warnColor,highlightcolor=highcolor) self.btnRefresh.grid(row=0, column=2) # # Start the download from findu # # # This gets the image and saves it to the local disk as image.png # # NOTE - will ideally want to conver this to GIF and save it using #the date as part of the filename so the net can be re-created #for reporting and to create a flipbook of the radar images # urllib.urlretrieve(self.findu, image.png) Image.open(image.png).save(image.gif) self.photo = PhotoImage(file=image.gif) # # create a canvas of the appropriate size for the image # self.w = Canvas(self.f, width=600, height=550) # # convert it into a photo item we can use in the display # self.netRadarImage = Label(self.w, image=self.photo) self.netRadarImage.image = self.photo self.w.grid(row=1, column=0, columnspan=3) self.netRadarImage.grid( row=1, column=0) def handlesExternalDisplayByClick(self): # # destroy the existing frame the radar is in # self.destroy() # # rebuild the radarWidgets # createRadarWidgets(frameRadar) def handlesRadarRefreshByClick(self): # # destroy the existing frame the radar is in # self.destroy() # # rebuild the radarWidgets # self.update() if __name__ == __main__: guiFrame = externalDisplay(AE5PL-10,fws) guiFrame.mainloop() The problem is that the window defined in the class never appears, and I don't know why. I would like to get all of the code for the window into a single file which I import, but since I can't make this work right, I don't want to invest the time yet.Eve worse, is that when I run the code as a standalone module and click on the close button, I am left with a tk window instead of the app actually closing. Any suggestions are appreciated. -- http://mail.python.org/mailman/listinfo/python-list
image resize doesn't work
I have the following chunk of code. Although it seems to execute fine, no errors, the image is never resized. What am I missing? imagePNG = Image.open(image.png) photo = ImageTk.PhotoImage(imagePNG canvasWidth = 300 canvasHeight = 275 photo = ImagePNG.resize((canvasWidth,canvasHeight),Image.ANTIALIAS) netRadarImage = Label(w, image=photo) -- http://mail.python.org/mailman/listinfo/python-list
Re: image resize doesn't work
On Aug 1, 2010, at 10:24 AM, rantingrick wrote: On Aug 1, 7:35 am, Chris Hare ch...@labr.net wrote: I have the following chunk of code. Although it seems to execute fine, no errors Not True! it contains syntax errors. Check the posted code and next time post all the code. -- http://mail.python.org/mailman/listinfo/python-list Hmmm... ok here is the code. I get no errors on my console when it execute urllib.urlretrieve(findu, image.png) logging.debug(createRadarWidgets(): radar download complete) logging.debug(createRadarWidgets(): user has radarPanelSize of + root.radarPanelSize.get()) # # open the image file # if os.path.exists(image.gif): ctime = os.stat(dbPath)[ST_CTIME] print ctime filetime = datetime.fromtimestamp(ctime) filetime = filetime.strftime(%Y%m%d%H%M%S) print str(filetime) #filetime = datetime(ctime).isoformat() #print ctime imagePNG = Image.open(image.png) #photo = ImageTk.PhotoImage(imagePNG) Image.open(image.png).save(image.gif) image = Image.open(image.gif) photo = PhotoImage(file=image.gif) #photoimg = ImageTk.PhotoImage(photo) # # NOTE: - will want to track the size of the image displayed based upon # the actual screen resolution # Full/External = 600x550 - full file size # Large = 450x412 # Medium = 300x275 # Small = 150x137 # if root.radarPanelSize.get() == Large: canvasWidth = 450 canvasHeight = 412 elif root.radarPanelSize.get() == Medium: canvasWidth = 300 canvasHeight = 275 elif root.radarPanelSize.get() == Small: canvasWidth = 150 canvasHeight = 137 logging.debug(createRadarWidgets(): creating image size + str(canvasWidth) + x + str(canvasHeight)) # # create a canvas of the appropriate size for the image # w = Canvas(f, width=canvasWidth, height=canvasHeight) if root.radarPanelSize.get() == Off: logging.debug(createRadarWidgets(): no net, no radar) netRadarImage = Label(w, text=No current radar) else: # # convert it into a photo item we can use in the display # # photo = photo.resize((canvasWidth,canvasHeight),Image.ANTIALIAS) netRadarImage = Label(w, image=photo) netRadarImage.image = photo w.grid(row=1, column=0, columnspan=3) netRadarImage.grid( row=1, column=0) -- http://mail.python.org/mailman/listinfo/python-list
Re: image resize doesn't work
On Aug 1, 2010, at 1:08 PM, Peter Otten wrote: Chris Hare wrote: On Aug 1, 2010, at 10:24 AM, rantingrick wrote: On Aug 1, 7:35 am, Chris Hare ch...@labr.net wrote: I have the following chunk of code. Although it seems to execute fine, no errors Not True! it contains syntax errors. Check the posted code and next time post all the code. -- http://mail.python.org/mailman/listinfo/python-list Hmmm... ok here is the code. I get no errors on my console when it execute urllib.urlretrieve(findu, image.png) I get a NameError on the very first line. urllib.urlretrieve(findu, image.png) Traceback (most recent call last): File stdin, line 1, in module NameError: name 'urllib' is not defined When you want to demonstrate a problem try to make a self-contained example, i. e. one that can be run without the need for us guess the surrounding code. Remove everything that is irrelevant for the problem like the logging in code below and the png/gif conversion gymnastics. Anyway, here is a self-contained demo (you have to pass the filename of an image on the commandline): import Tkinter import ImageTk import Image import sys [filename] = sys.argv[1:] image = Image.open(filename) root = Tkinter.Tk() frame = Tkinter.Frame(root) frame.pack() label = Tkinter.Label(root) label.pack() def make_resize(percent): def resize(): width, height = image.size label.image = label[image] = ImageTk.PhotoImage( image=image.resize((width*percent//100, height*percent//100))) return resize make_resize(100)() pairs = [ (Small, 20), (Medium, 50), (Original, 100), (Big, 200)] for i, (text, percent) in enumerate(pairs): button = Tkinter.Button(frame, text=text, command=make_resize(percent)) button.grid(row=0, column=i) root.mainloop() Peter -- http://mail.python.org/mailman/listinfo/python-list Thanks for the help. My one week of python is getting a workout. I have shortened it all down and made it a standalone example, using yours as a model. Your example, works, but it will take a lot of effort to retrofit it into the code I have. (which is maybe not a bad idea,). Anyway from Tkinter import * import ImageTk import Image import sys def sizeit(filename): image = Image.open(filename) w,h = image.size print w, h photo = ImageTk.PhotoImage(file=filename) canvasWidth = 450 canvasHeight = 412 image = image.resize((canvasWidth,canvasHeight),Image.ANTIALIAS) w,h = image.size print w, h netRadarImage = Label(frame, image=image) netRadarImage.image = photo w.grid(row=1, column=0, columnspan=3) netRadarImage.grid( row=1, column=0) [filename] = sys.argv[1:] root = Tk() frame = Frame(root) frame.grid() sizeit(filename) root.mainloop() Just like yours it takes a filename. Unlike yours, mine gets an error that I can't figure out and is likely the root of the problem. When I run this code I get 600 550 == ORIGINAL image size 450 412 == resized image size Traceback (most recent call last): File zztest.py, line 26, in module sizeit(filename) File zztest.py, line 16, in sizeit netRadarImage = Label(frame, image=image) File /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py, line 2466, in __init__ Widget.__init__(self, master, 'label', cnf, kw) File /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py, line 1932, in __init__ (widgetName, self._w) + extra + self._options(cnf)) _tkinter.TclError: image Image.Image image mode=P size=450x412 at 0x1016095A8 doesn't exist So, my problem appeared to be the resize, but in fact is just getting it onto the label. What am I doing wrong? -- http://mail.python.org/mailman/listinfo/python-list
beginner python GUI question
I hope I can explain this correctly. I have a GUI, which is already being processed by a mainloop. I want to be able to open a second window so the user can interact with specific information in the second window. I pulled together this code example from Tkinter import * class Net: def __init__(self,tkWin): self.window = tkWin def show(self,t): self.l = Label(self.window,text=t) self.l.grid() button = Button(self.window, text=Again) button.bind(Button-1, self.Again) button.grid() def Again(self,event): win3 = Tk() x = Net(win3) x.show(window 3) root = Tk() root.title = test f = Frame(root,bg=Yellow) l = Label(f,text=window 1) f.grid() l.grid() win2 = Tk() x = Net(win2) x.show(window 2) if __name__ == __main__: root.mainloop() Is this the right way to do things, or would you suggest something different? Thanks, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: image resize doesn't work
And I see now what I did wrong - thanks for putting up with the questions. On Aug 1, 2010, at 4:32 PM, Peter Otten wrote: Chris Hare wrote: Thanks for the help. My one week of python is getting a workout. I have shortened it all down and made it a standalone example, using yours as a model. Your example, works, but it will take a lot of effort to retrofit it into the code I have. (which is maybe not a bad idea,). You mean retrofit something that works into something tha doesn't? Seriously, you should never be afraid to throw away code, especially while you're still in the early phase of learning the language. def sizeit(filename): image = Image.open(filename) Now you have an Image w,h = image.size print w, h photo = ImageTk.PhotoImage(file=filename) and now a photo, both created from the same file but otherwise independent canvasWidth = 450 canvasHeight = 412 image = image.resize((canvasWidth,canvasHeight),Image.ANTIALIAS) Now you have a new resized Image w,h = image.size print w, h netRadarImage = Label(frame, image=image) Label(image=...) expects a PhotoImage netRadarImage.image = photo w.grid(row=1, column=0, columnspan=3) Hmm... netRadarImage.grid( row=1, column=0) Here's the fixed code: def sizeit(filename): image = Image.open(filename) canvasWidth = 450 canvasHeight = 412 image = image.resize((canvasWidth, canvasHeight),Image.ANTIALIAS) photo = ImageTk.PhotoImage(image=image) netRadarImage = Label(frame, image=photo) netRadarImage.image = photo netRadarImage.grid(row=0, column=0) In plain English: - open the Image using the PIL - resize it - wrap it into a PhotoImage - wrap the PhotoImage into a Tkinter.Label either by passing it to the initialiser or by assigning to label[image] - make sure the PhotoImage isn't garbage-collected e. g. by assigning to label.image Peter -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: image resize doesn't work
Thanks Peter - I know what I said sounded stupid :-) I have been working with Python for a week and as you know sometimes it is easier to learn by seeing what you did wrong as compared to what should have been done with the same example. I loved your code by the way - Thanks for help just another beginner On Aug 1, 2010, at 4:32 PM, Peter Otten wrote: Chris Hare wrote: Thanks for the help. My one week of python is getting a workout. I have shortened it all down and made it a standalone example, using yours as a model. Your example, works, but it will take a lot of effort to retrofit it into the code I have. (which is maybe not a bad idea,). You mean retrofit something that works into something tha doesn't? Seriously, you should never be afraid to throw away code, especially while you're still in the early phase of learning the language. def sizeit(filename): image = Image.open(filename) Now you have an Image w,h = image.size print w, h photo = ImageTk.PhotoImage(file=filename) and now a photo, both created from the same file but otherwise independent canvasWidth = 450 canvasHeight = 412 image = image.resize((canvasWidth,canvasHeight),Image.ANTIALIAS) Now you have a new resized Image w,h = image.size print w, h netRadarImage = Label(frame, image=image) Label(image=...) expects a PhotoImage netRadarImage.image = photo w.grid(row=1, column=0, columnspan=3) Hmm... netRadarImage.grid( row=1, column=0) Here's the fixed code: def sizeit(filename): image = Image.open(filename) canvasWidth = 450 canvasHeight = 412 image = image.resize((canvasWidth, canvasHeight),Image.ANTIALIAS) photo = ImageTk.PhotoImage(image=image) netRadarImage = Label(frame, image=photo) netRadarImage.image = photo netRadarImage.grid(row=0, column=0) In plain English: - open the Image using the PIL - resize it - wrap it into a PhotoImage - wrap the PhotoImage into a Tkinter.Label either by passing it to the initialiser or by assigning to label[image] - make sure the PhotoImage isn't garbage-collected e. g. by assigning to label.image Peter -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
how best to clear objects from a frame
Here is the situation: I have a window with a bunch of widgets in it. I want to clear the objects in a given frame and recreate them to update them. The example below destroys the top level frame, and so I can't recreate the widgets. I am likely doing this wrong. should I be doing this in a class? Thanks for the help. from Tkinter import * def createLeftWidgets(left): # # Add the Net Status Section # conditions = LabelFrame(left, text=Net Conditions,bg=Gray) conditions.grid(row=0,column=0); button = Button(conditions, text=Refresh, command=refreshNetConditions, highlightbackground=Green) button.grid(row=0,column=1, sticky=E) cText = Text(conditions,bg=Gray) cText.insert(END, root.netHistory.get()) cText.config(height=12,width=40) cText.grid(row=1,column=0,columnspan=2) status = LabelFrame(left, text=Net Details,bg=Gray) status.grid(row=1,column=0,sticky=N+E+W+S); lblNetNumber = Label(status, text=Net Number) lblNetNumber.grid( row=19, column=0, columnspan=2,sticky=W) return(conditions) def refreshNetConditions(): global frameLeft frameLeft.destroy() root.netHistory.set( inserting text\n + root.netHistory.get()) createLeftWidgets(frameLeft) root = Tk() root.netHistory = StringVar() root.netHistory.set(goes into the text widget) frame = Frame(root) frame.grid() frameLeft = createLeftWidgets(frame) root.mainloop() -- http://mail.python.org/mailman/listinfo/python-list