First Tkinter application. Comments please?
Gerrit Holl
gerrit.holl at pobox.com
Mon Dec 20 16:05:20 EST 1999
Hello,
I just created my first Tkinter.Canvas application. Can someone please
be kind enough to comment on the code? Maybe my ``problem'' could be solved
much easier...
# cut here
from Tkinter import *
UP = 98 # keycodes
LEFT = 100
RIGHT = 102
DOWN = 104
class App:
id = 0
def __init__(self, root):
self.root = root
self.draw = Canvas(self.root, width=400, height=400)
self.draw.create_oval(0, 0, 10, 10, tags="it", fill="blue")
self.draw.pack()
# What's better: this, or binding <KeyPress> and ignoring everything
# that's not a keycode of one of these?
self.root.bind("<KeyPress-Up>", self.move_it)
self.root.bind("<KeyPress-Down>", self.move_it)
self.root.bind("<KeyPress-Left>", self.move_it)
self.root.bind("<KeyPress-Right>", self.move_it)
self.root.mainloop()
def move_it(self, *args):
# Because bind gives an argument, which I will always need, but
# after doesn't give the argument.
if len(args):
self.dir = args[0]
if self.dir.keycode == UP:
self.draw.move("it", 0, -1)
elif self.dir.keycode == DOWN:
self.draw.move("it", 0, 1)
elif self.dir.keycode == RIGHT:
self.draw.move("it", 1, 0)
elif self.dir.keycode == LEFT:
self.draw.move("it", -1, 0)
# Because otherwise, it gets called twice as many times.
if self.id:
self.root.after_cancel(self.id)
self.id = self.root.after(10, self.move_it)
App(Tk())
# cut here
If the code is ``good'' (I don't think it is), it might suit well for an
example in the Demo/tkinter/ dir. It costed me very much time to find out
how I had do do the after_cancel. I looked in the source, saw the
method and thought "what is the argument? "it"? "move_it"?". I ended up
looking in the source of idle.
I think that if this example is OK, it's a good example of using keycodes
and preventing the 'self.root.after(...)' to be executed too much.
regards,
Gerrit `who loves Tkinter now he finally understands it'.
--
"The IETF motto is 'rough consensus and running code'"
-- Scott Bradner (Open Sources, 1999 O'Reilly and Associates)
9:54pm up 7:39, 10 users, load average: 0.05, 0.05, 0.01
More information about the Python-list
mailing list