首页 > 解决方案 > 在 TKinter 的回调函数中取消选择小部件

问题描述

我在 python2 中使用了 TKinter。

我的代码如下。

from Tkinter import *  


class Application(Frame):
    def __init__(self, master=None,w=1000,h=600):
        Frame.__init__(self, master)
        self.createWidgets(master,w,h)

    def getRadio(self,widget):
        widget.deselect()


    def createWidgets(self, master,w,h):
        ConfigPane=Frame(master,bg='lightblue',width=int((w/6)*4),height=int(h/3),padx=5,pady=5)
        DisplayPane=Frame(master,bg='DarkOliveGreen1',width=int((w/6)*4),height=int((h/3)*2),padx=5,pady=5)
        HyperPane=Frame(master,bg='khaki1',width=int((w/6)*2),height=h,padx=5,pady=5)
        # layout all of the main containers
        root.grid_rowconfigure(0, weight=1)
        root.grid_rowconfigure(1, weight=1)        
        ConfigPane.grid(row=0,column=0,columnspan=4,rowspan=1, sticky=W+N)
        DisplayPane.grid(row=1,columnspan=4,rowspan=2, sticky=W+S)
        HyperPane.grid(row=0,column=5,columnspan=2,rowspan=3, sticky=E+N+S)
        # create the widgets for the top frame
        var=StringVar()
        RegNet = Radiobutton(ConfigPane, text='RegNet',variable=var,pady=10,padx=10,width=10,anchor='w',command=lambda:self.getRadio(RegNet))
        RegNet.grid(row=0,column=0)           
        InceptionNet = Radiobutton(ConfigPane, text='InceptionNet',variable=var,pady=1,padx=10,width=10,anchor='w',command=lambda:self.getRadio(InceptionNet))
        InceptionNet .grid(row=1,column=0)
        ResNet = Radiobutton(ConfigPane, text='ResNet',variable=var,pady=8,padx=10,width=10,anchor='w',command=lambda:self.getRadio(ResNet))
        ResNet.grid(row=2,column=0)  

if __name__ == "__main__":
    root = Tk()
    width = root.winfo_screenwidth()
    height = root.winfo_screenheight()
    root.geometry(str(width)+'x'+str(height))
    app = Application(master=root,w=width,h=height)
    app.master.title('Deep Learning Reconfigurable Platform')
    app.mainloop()
    root.destroy()

当我单击单选按钮时,按钮上的黑点应该消失,但事实并非如此。我怎样才能让它工作?

标签: pythontkinter

解决方案


每个单选按钮都需要一个 distinct value,否则它们都具有相同的值并因此显示相同的状态。该值是 tkinter 如何知道应该选择一组按钮中的哪个按钮。

您可能不应该deselect在回调中调用 - 这会使您的按钮实际上无用,因为用户选择一个的任何尝试都会导致他们单击的任何内容立即被取消选择。他们将无法选择任何东西。


推荐阅读