首页 > 解决方案 > 为什么我不能指定默认选择的单选按钮?

问题描述

我正在使用 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(),但这似乎也不起作用。我错过了什么?

编辑:添加其余代码以显示我如何使用类和函数来操作窗口。

标签: pythonuser-interfacetkinterradio-button

解决方案


这是因为它是函数selection内部的一个局部变量createData(),它会在函数完成后被垃圾回收。

更改selection为实例变量self.selection


推荐阅读