【问题标题】:Tkinter obtain the value select from CheckbuttonTkinter 从 Checkbutton 中获取值选择
【发布时间】:2020-09-30 18:13:37
【问题描述】:

我是 tkinter 的新手,我正在尝试从复选按钮获取值选择到我的其他脚本,但在我选择并单击“选择”按钮后,它一直向我显示下面的错误。

这是我的脚本:

from tkinter import * 

root = Tk()

options =  ["All","Happy","Sad","Angry","Emotional","Disgust","None of above"]

message = Label(root, text ='Select how you feel today: ')
message.pack()

for x in range(len(options)):
    choose = Checkbutton(root, text= options[x]).pack(anchor=W)
        

def selected():
    print(choose.get())
        
result = Button(root, text='Select', width=15, command = selected).pack(pady =6, anchor=SE)
cancel = Button(root, text='Cancel', width=15, command = root.destroy).pack(pady=6,anchor=SE)

root.mainloop()

  File "C:\Users\Desktop\Python\temp.py", line 22, in selected
    print(choose.get())
AttributeError: 'NoneType' object has no attribute 'get'

我需要如何更改我的代码,以便我可以从我的复选框中获取我勾选的值?

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    每个复选框都需要变量。我的建议是将这些变量存储在字典 all_vars 中,以便您可以轻松访问它们:

    from tkinter import * 
    
    root = Tk()
    
    options =  ["All","Happy","Sad","Angry","Emotional","Disgust","None of above"]
    
    message = Label(root, text ='Select how you feel today: ')
    message.pack()
    
    all_vars = {}
    for opt in options:
        var = IntVar()
        choose = Checkbutton(root, text=opt, variable=var).pack(anchor=W)
        all_vars[opt] = var
            
    
    def selected():
        for opt in options:
            print(opt, all_vars[opt].get())
            
    result = Button(root, text='Select', width=15, command = selected).pack(pady =6, anchor=SE)
    cancel = Button(root, text='Cancel', width=15, command = root.destroy).pack(pady=6,anchor=SE)
    
    root.mainloop()
    

    输出(如果被选中,你会得到1,如果不是,你会得到0):

    All 0
    Happy 0
    Sad 0
    Angry 0
    Emotional 0
    Disgust 0
    None of above 0
    All 0
    Happy 0
    Sad 0
    Angry 1
    Emotional 0
    Disgust 0
    None of above 0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-10
      相关资源
      最近更新 更多