tkinter radio buttons does not work inside function
I am trying to write a GUI (in fact a PyMOL plugin) with radio buttons. I need the radio buttons to be inside a function. I have two problems (if the radio buttons are outside a function I don´t have any problem):
1) the last two radio button looks gray and checked. (I think the correct behavior should be only one checked and none gray) setting a different default value (using ref_value.set()) does not change anything
2) I always get the default value ("1" in this example) when hit the submit button.
from Tkinter import *
def __init__(self):
"""this adds the Plugin to the PyMOL menu"""
self.menuBar.addmenuitem('Plugin', 'command',
'Plugin name',
label = 'plugin',
command = lambda : draw_gui())
def draw_gui():
global v
master = Tk()
master.title(' title ')
Button(master, text='Submit', command=submit).pack(side=BOTTOM)
v = StringVar()
v.set(1)开发者_Python百科
Radiobutton(master, text='option 1', variable=v, value=1).pack(side=LEFT)
Radiobutton(master, text='option 2', variable=v, value=2).pack(side=LEFT)
Radiobutton(master, text='option 3', variable=v, value=3).pack(side=LEFT)
master.mainloop()
def submit():
print v.get()
Thanks in advance
I should set the master explicitly, otherwise it will use the PyMOL GUI as master.
v = StringVar(master=master)
PS: thanks Thomas Holder for the answer.
It works for me (I copied your code and added the lines from Tkinter import *
and if __name__ == "__main__": draw_gui()
which I assume you have too). All the radio buttons work and I get 1, 2, 3 as appropriate in the output.
So if you are running the same code, there is a problem with the environment. I have Tkinter 73770 and Python 2.6.5 on Ubuntu 10.04 and am running the script from the command line.
Are you perhaps trying to run it from IDLE? That often doesn't play nice with other scripts that use Tkinter, because it is written in Tkinter itself. If so, try running from the command line instead.
精彩评论