Tkinter problem
Russell E. Owen
no at spam.invalid
Mon Jun 23 16:09:06 EDT 2003
In article <kueJa.1349$os2.18711 at news2.e.nsc.no>,
"Eirik" <hannibalkannibal at yahoo.no> wrote:
>Look at this code(I am not sure whether it is correct or not, I am in
>Windoze and have no possibility to check):
>--CODE BEGIN--
>
>from Tkinter import *
>
>root = Tk()
>...
>root.b1 = Button(root, text = "Button", command = root.t.set("Test-Text"))
Others have already pointed out that the function gets called when you
define root.b1, not when the button is pressed. You can define a new
function that takes no arguments to handle the problem -- you can even
define the function "on the fly" (which is what I usually do), as in:
def tset():
root.t.set("Text-Text")
root.b1 = Button(root, text = "Button", command = tset)
If you find yourself doing this a lot you may want to look up "currying"
functions. There is an example class for this in my Tkinter summary
<http://www.astro.washington.edu/owen/TkinterSummary.html>.
....
However...my main reason for writing was to ask why you are storing your
widgets as attributes of root?
You have some really good reason, but my first guess is you are simply
trying to make your Python Tkinter code look more like Tk code. If so,
please don't. Root is an object that already has lots of useful
attributes (functions and variables that it needs to do its job). You
can get a full list via dir(root). By adding more attributes that aren't
necessary you risk collision and also confusion of others who read your
code.
In Tk widgets are named according to their hierarchy, and you end up
with names that are something like .frame1.button2.
But in Tkinter you don't do it that way. You specify the hierarchy by
specifying a "master" (the first argument to Button, Frame, etc.) when
you create a widget . Tkinter takes care of the rest (automatically
generating a suitable Tk name).
When using Tkinter you'll usually want to use a variable to hold your
widget:
b1 = Button(root-or-other-master, ...)
(or if you are writing a class and want to keep a reference to b1 for
users of that class then self.b1 = ...)
-- Russell
More information about the Python-list
mailing list