Can someone provide me with some example code. I am fairly fluent with python but can't figure this out. So i will be generating a list with say "x" elements from other code. I need Tkinter to display a "x" buttons that can be checked on or off. Then once the user has selected whichever ones they want, they will press GO and more code will execute on only the items in the list that are selected. So basically i just need to make something True or False (or 1 or 0) by using the checkbuttons in Tkinter. If someone can show me how to do this using Classes id love to see it. Thanks!!
+2
A:
import Tkinter as tk
def printVar():
print 'var is', var.get()
root = tk.Tk()
var = tk.IntVar()
c = tk.Checkbutton(root, text='Check me', variable=var, command=printVar)
c.pack()
root.mainloop()
Take a look at Tkinter page at the python wiki.
Edit
import Tkinter as tk
def printOpts():
for opt, val in zip(options, checkboxes):
print opt + ': ' + str(bool(val.get()))
options = ['eggs', 'apples', 'pears']
checkboxes = []
root = tk.Tk()
for opt in options:
v = tk.IntVar()
checkboxes.append(v)
c = tk.Checkbutton(root, text=opt, variable=v)
c.pack()
btn = tk.Button(root, text='Print options', command=printOpts)
btn.pack()
root.mainloop()
mg
2010-09-01 08:58:05
yes this works for 1 checkbutton, but i need x checkbuttons with unique variables...
Alex
2010-09-01 15:20:24
@Alex: enclose it in a for loop...
mg
2010-09-01 17:39:53
that doesnt work because then the variables get reassigned each time and are not carried outside of the for loop (except for the last one). The solution is to define that function with an additional line of code adding to a list, that will be available outside the function. Then it works!
Alex
2010-09-02 01:28:55
The use of a `list` was implicit even not oblivious, then you could use a loop as well. Look at the new code.
mg
2010-09-02 06:28:20
I personally prefer using a dict rather than a list of checkboxes (checkboxes={}...checkboxes[opt]=v...)
Bryan Oakley
2010-09-02 15:25:05
A:
Makes a nice toggle button
import Tkinter
class TkToggle(Tkinter.Tk):
def __init__(self, parent):
Tkinter.Tk.__init__(self, parent)
self.parent = parent
self.initialize()
def initialize(self):
global toggle
toggle = 0
self.Button = Tkinter.Label(self, text='X', relief='ridge')
self.Button.pack(ipadx=15,ipady=15)
self.Button.bind('<ButtonRelease-1>', self.Toggle)
def Toggle (self, event):
global toggle
if toggle == 0:
toggle = 1
self.Button.configure(text = '')
print 'A'
else:
toggle = 0
self.Button.configure(text = 'X')
print 'B'
if __name__ == "__main__":
app = TkToggle(None)
app.mainloop()
Anteater7171
2010-09-06 19:54:54
Hey that works well, but again in that format, that only allows for a single toggle button, whereas i want to make x toggle buttons. Its easy to just make a list inside the button function that stores unique info for each button. Thanks!
Alex
2010-09-10 03:00:58