python - 为什么我不能指定默认选择的单选按钮?
问题描述
我正在使用 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(),但这似乎也不起作用。我错过了什么?
编辑:添加其余代码以显示我如何使用类和函数来操作窗口。
解决方案
这是因为它是函数selection
内部的一个局部变量createData()
,它会在函数完成后被垃圾回收。
更改selection
为实例变量self.selection
。
推荐阅读
- jquery - 如何在ajax jquery中给出基本url
- java - 检查给定的字符串是否可以由给定的一组字符串组成
- intellij-idea - 如何在 IntelliJ 中以制表符宽度直观地换行?
- scheme - Racket - 需要整个目录的文件
- android - 寻找 3 个或更多地点之间的最短路线(谷歌地图路线)
- excel - 如何通过 POST VBA Httprequest 传递登录名和密码?
- python - 如何在 python 中生成随机稀疏厄米特矩阵?
- ios - 如何区分 tableViewCell 中的按钮,在 tableView 中重复使用?
- twitter-bootstrap - 为什么我的响应式 Web 模板在手机上不起作用?
- html - 单击时如何获取标签以检查无线电输入?