【问题标题】:tkinter Radiobuttons not displaying value in classtkinter 单选按钮未在类中显示值
【发布时间】:2021-07-25 00:57:48
【问题描述】:

我目前是一名正在学习 python 的大学生,并且在使用 tkinter 时遇到了一些 Radiobutton 问题。当使用多个类时,我的单选按钮不会更新它们的值,并且总是会打印出.set() 方法的值。这是一段类似于我实验室中的代码的 sn-p,但它只是问题区域。

import matplotlib
matplotlib.use("TkAgg")
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
from matplotlib.figure import Figure


class test(tk.Tk):
    def __init__(self):
        super().__init__()
        self.TOPNUM=15


class dialogWindow(test):
    def __init__(self):
        super().__init__()

        self.rc=tk.IntVar()
        self.rc.set(20)


        self.radio1=tk.Radiobutton(self,text="1",value=1,variable=self.rc,command=self.rc.get())
        self.radio2=tk.Radiobutton(self,text="2",value=2,variable=self.rc,command=self.rc.get())

        self.button=tk.Button(self,text="CLick Me!",command=lambda : self.clicked(self.rc.get()))

        self.radio1.pack()
        self.radio2.pack()
        self.button.pack()
        self.rc.set(20)

    def clicked(self,value):
        print(value)


def run():
    win=test()
    win.title("Top Colleges")
    win.minsize(200,200)
    header=tk.Label(win,text="College Lookup",fg="blue",font=15)
    header.pack()

    dataButton=tk.Button(win,text="By Data",width=8, command= lambda : dialogWindow())

    dataButton.pack()

    win.mainloop()

run()

但是,当我尝试只在一个类中编写它时,它确实有效,但我不知道为什么。

class dialogWindow(tk.Tk):
    def __init__(self):
        super().__init__()

        self.rc=tk.IntVar()
        self.rc.set(20)

        self.radio1=tk.Radiobutton(self,text="1",value="1",variable=self.rc,command=self.rc.get())
        self.radio2=tk.Radiobutton(self,text="2",value="2",variable=self.rc,command=self.rc.get())

        self.button=tk.Button(self,text="CLick Me!",command=lambda : self.clicked(self.rc.get()))

        self.radio1.pack()
        self.radio2.pack()
        self.button.pack()
        self.rc.set(1)

    def clicked(self,value):
        print(value)


def run():
    win=dialogWindow()
    win.minsize(200,200)
    dataButton=tk.Button(win,text="By Data",width=8, command= lambda:dialogWindow())

    dataButton.grid(row=1,column=2,padx=5)

    win.mainloop()
run()

【问题讨论】:

    标签: python oop user-interface tkinter inheritance


    【解决方案1】:

    解释很简单,因为继承而创建了两个Tk()实例。现在你必须指定IntVar() 应该属于哪个实例,因为它总是将自己设置为第一个创建的实例(win),但在这里你不希望这样。所以:

    class dialogWindow(test):
        def __init__(self):
            super().__init__()
            
            self.rc=tk.IntVar(self)
            .....
    

    【讨论】:

    • 哇,这么简单的解决方案。谢谢你的解释!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 2021-06-10
    • 2020-08-10
    相关资源
    最近更新 更多