from Tkinter import *; class MyButton(Button): def callback(self): pass; def __init__(self,parent,text=None): Button.__init__(self,parent,command=self.callback,text=text); window = Tk(); for string in ["a","b"]: button = MyButton(window,text=string); button.pack(); counter = 0; # ??? mainloop();In this example I would like to update the counter to keep track of how many button presses there have been (either a or b, or any button if I extend the example). I'm interested in both the "right" way and the way that would commonly be used. Google has failed me entirely.
def callback(self): global counter counter += 1Three things to note:
from Tkinter import *;
class MyButton(Button):
def callback(self):
self.counter_ref[0] += 1
def __init__(self,parent,text=None, counter_ref):
Button.__init__(self,parent,command=self.callback,text=text);
self.counter_ref = counter_ref
window = Tk();
counter = [0];
for string in ["a","b"]:
button = MyButton(window,text=string,counter);
button.pack();
mainloop();
window = Tk(); class Counter: def __init__(self): self.value = 0 def increment(self): self.value += 1 counter = Counter() for string in ["a","b"]: button = Button(window,text=string,command=counter.increment); button.pack(); mainloop();
import Tkinter as tk
class UI(object):
def __init__(self):
self.clickcount = 0
window = tk.Tk()
for buttontext in ["a", "b"]:
button = tk.Button(window, text=buttontext, command=self.onbuttonclick)
button.pack()
def onbuttonclick(self):
self.clickcount += 1
def go(self):
tk.mainloop()
def main():
ui = UI()
ui.go()
main()
If you still want to use your MyButton class, you could set up MyButton.__init__() function to take a "UI callback" argument, then call that from MyButton.callback().
Pass a callback into the MyButton constructor in your loop, use that callback as the command param in the button ctor. In the callback increment the counter.
posted by Ad hominem at 1:36 PM on April 18, 2011