【问题标题】:Tkinter checkbox 'Name not defined'Tkinter 复选框'未定义名称'
【发布时间】:2016-09-28 17:46:52
【问题描述】:

我目前正在编写一个使用 Tkinter 为用户提供图形界面的应用程序。

该应用程序运行良好,最近我决定添加一些复选框,其想法是当用户选中其中一个框时,另一组文本会通过 API 发送。

我有输入框,我可以完美地工作,但是由于某种原因,每当我尝试检索复选框的值时,我都会收到以下错误:

     if check.get():
NameError: name 'check' is not defined

对于我的生活,我无法弄清楚为什么会弹出这个错误,这是我的其余代码,为了更清楚,我已经删除了输入框的工作代码。

from tkinter import *

class GUI:
    def __init__(self, master):
         check = IntVar()



         self.e = Checkbutton(root, text="check me", variable=check)
         self.e.grid(row=4, column=2)

         self.macro_button = Button(master, text="Test Button", command=self.test)
         self.macro_button.grid(row=11, column=1)



      def test(self):
           if check.get():
                print('its on')
           else:
                print('its off')



root = Tk()
root.resizable(width=False, height=False)
my_gui = GUI(root)
root.mainloop()

当我运行此代码并按下标有“测试按钮”的按钮时,我的终端中就会出现错误。

有人知道为什么我的复选框会发生这种情况,而不是我的输入框吗?

编辑:

对我来说更奇怪的是,我在网上找到的这段代码是为了教你如何使用 tkinter 复选框,它就像一个魅力,它几乎和我的一样:

import tkinter as tk

root = tk.Tk()

var = tk.IntVar()
cb = tk.Checkbutton(root, text="the lights are on", variable=var)
cb.pack()

def showstate():
    if var.get():
        print ("the lights are on")
    else:
        print ("the lights are off")

button = tk.Button(root, text="show state", command=showstate)
button.pack()

root.mainloop()

【问题讨论】:

    标签: python checkbox tkinter


    【解决方案1】:

    您只需要使用self 将check 设为实例变量。

    I.E

    class GUI:
        def __init__(self, master):
            self.check = IntVar()
    
    
    
            self.e = Checkbutton(root, text="check me", variable=self.check)
            self.e.grid(row=4, column=2)
    
            self.macro_button = Button(master, text="Test Button", command=self.test)
            self.macro_button.grid(row=11, column=1)
    
    
    
        def test(self):
            if self.check.get():
                print('its on')
            else:
                print('its off')
    
    
    
    root = Tk()
    root.resizable(width=False, height=False)
    my_gui = GUI(root)
    root.mainloop()
    

    您在网上找到的示例是以“内联”样式编写的 - 在您的 GUI 变大并且需要使用/传递许多方法和变量之前,这很好。

    【讨论】:

    • 非常感谢您的回复,它工作得很好,很明显我是新手哈哈!当我不必对输入框中输入的文本变量执行相同操作时,为什么我必须使用 self 将其设为实例变量? @Luke.py
    • 什么是输入框?你的意思是条目小部件?我可以在您的代码中看到其中的任何一个! :S 这解决了您的问题吗?
    • 是的,我的意思是入口小部件,我知道我把它们遗漏了,但我只是问了一个一般的 python 问题。是的,我的问题已经解决了,谢谢@luke.py
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多