【发布时间】:2020-11-29 09:19:03
【问题描述】:
我正在使用 Python 的 tkinter 模块制作一个简单的 GUI,但我在使用单选按钮时遇到了很多麻烦。我希望默认选择第一个,但一开始就选择了另外两个。此外,当我将光标移到窗口上时,第一个被选中(我没有单击),因此所有 3 个都显示为选中状态。我的代码:
import tkinter as tk
class openGUI(object):
def __init__(self):
# title of window
window.title("DUNE LArTPC Simulator")
# label for choices
self.question = tk.Label(window, text = "Do you want to create new or analyse existing data?")
self.question.grid(row = 0, column = 0, columnspan = 3)
# buttons corresponding to choices
self.createBtn = tk.Button(window, text = "Create", command = self.createData)
self.analyseBtn = tk.Button(window, text = "Analyse", command = self.analyseData)
self.createBtn.grid(row = 1, column = 0)
self.analyseBtn.grid(row = 1, column = 2)
def analyseData(self):
"""
Not implemented yet.
"""
pass
def createData(self):
# edit window to display new widgets (irritating to have lots of windows open!)
window.title("Select variable")
self.question.destroy()
self.createBtn.destroy()
self.analyseBtn.destroy()
# text in window
variableQ = tk.Label(window, text = "Please select Independent variable for dataset:")
variableQ.grid(row = 0, column = 0, columnspan = 3)
# radioselect variable
selection = tk.StringVar()
selection.set("lifetime")
# radioselect buttons
lifetimeBtn = tk.Radiobutton(window, variable = selection, value = "lifetime", text = "Lifetime")
elecNoiseBtn = tk.Radiobutton(window, variable = selection, value = "electronic", text = "Electronic Noise")
radioactivityBtn = tk.Radiobutton(window, variable = selection, value = "radioactive", text = "Radioactivity")
lifetimeBtn.grid(row = 1, column = 0)
elecNoiseBtn.grid(row = 1, column = 1)
radioactivityBtn.grid(row = 1, column = 2)
# create window
window = tk.Tk()
# create class object with methods to populate
# window with widgets
initWin = openGUI()
# enter mainloop
window.mainloop()
运行上面的代码给了我:
我尝试过使用lifetimeBtn.select() 方法而不是设置StringVar(),但这似乎也不起作用。我错过了什么?
编辑:添加其余代码以显示我如何使用类和函数来操作窗口。
【问题讨论】:
-
请提供minimal reproducible example。看起来这些代码的部分或全部属于一个类和/或函数,但没有类或方法定义。
-
你的代码适合我
-
您的代码运行良好。但是如果我将所有
variable = selection更改为variable = 'selection',那么我会遇到同样的问题。 -
@BryanOakley 我已经添加了我的其余代码,显示了我用来制作 GUI 的类和函数结构。你现在能看到我的错误吗?!谢谢!
-
@CoolCloud 感谢您的尝试。我已经添加了显示我正在使用的类的其余代码 - 你现在能看到错误吗?
标签: python user-interface tkinter radio-button