python单选按钮重置_python–Tkinter单选按钮初始化错误存储变量对象的位置(StringVar,v,在您的情况下)必须保持不变,以便这种奇怪的⾏为不会出现.我的猜测是我们看到这种⾏为因为v超出了范围,出了问题.除了使⽤全局之外,我⽆法想到从函数中执⾏此操作的⽅法.
破码:
from Tkinter import *
def App(master):
v = StringVar()
v.set('python')
lable1 = Label(master, text=' hovering over below radio buttons will cause them to look like they are selected')
lable1.pack()
runtimeFrame = Frame(master, relief=GROOVE, borderwidth=3)
runtimeFrame.pack(fill=X, pady=5, padx=5)
for mode in ['java', 'python', 'jython']:
b = Radiobutton(runtimeFrame, text=mode, variable=v, value=mode, indicatoron=1)
b.pack(side=LEFT)
if __name__ == '__main__':
master = Tk()
App(master)
mainloop()
⽰例修复:
from Tkinter import *
def App(master, radio_var):
htmlradio设置默认的按钮radio_var.set('python')
lable1 = Label(master, text=' hovering over below radio buttons will cause them to look like they are selected')
lable1.pack()
runtimeFrame = Frame(master, relief=GROOVE, borderwidth=3)
runtimeFrame.pack(fill=X, pady=5, padx=5)
for mode in ['java', 'python', 'jython']:
b = Radiobutton(runtimeFrame, text=mode, variable=radio_var, value=mode, indicatoron=1)
b.pack(side=LEFT)
if __name__ == '__main__':
master = Tk()
radio_var = StringVar()
App(master, radio_var)
mainloop()
考虑⼀下,如果你有多个需要持久化的变量,你可以传⼊⼀个变量列表或字典.
此外,如果“必须在函数中”是作业分配要求,请考虑将代码包装在类中.我不是tk专家,但这似乎是组织代码的⾸选⽅式.
⽰例修复2:
from Tkinter import *
class App(object):
def __init__(self, master):
self.radio_var = StringVar()
self.radio_var.set('python')
lable1 = Label(master, text=' hovering over below radio buttons will cause them to look like they are selected') lable1.pack()
runtimeFrame = Frame(master, relief=GROOVE, borderwidth=3)
runtimeFrame.pack(fill=X, pady=5, padx=5)
for mode in ['java', 'python', 'jython']:
b = Radiobutton(runtimeFrame, text=mode, variable=self.radio_var, value=mode, indicatoron=1)
b.pack(side=LEFT)
if __name__ == '__main__':
master = Tk()
app = App(master)
mainloop()
注意⼀个微⼩的变化
app = App(master)
这是必需的,以便App实例不会过早地进⾏垃圾回收.这将有效地将self.radio_var拉出范围,我们⼜回到了第⼀个⽅向.
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论