Python 3.4.1,Tkinter 8.6.3,class 内的事件在寻找 class 按钮时抛出 'Name not defined' 错误

Python 3.4.1, Tkinter 8.6.3, Event within class throwing 'Name not defined' error when looking for class button

我试图在用户点击另一个按钮后将按钮的状态设置为 'normal',但无论出于何种原因,该事件似乎无法找到我正在引用的按钮并抛出NameError: name 'rawButton' is not defined' 错误。我尝试在按钮前添加 self.,但随后出现 self not defined 错误。我已经看遍了,我终其一生都无法弄清楚为什么这不起作用……在此先感谢您提供的任何帮助。

相关代码如下:

import tkinter as tk
from imaging import *

class MainClass:
    root = tk.Tk()
    root.title('Main Window')

    def call_bgFrame(self):    
        self.background = bgFrame()
        rawButton.config(state = 'normal')

    labels = ['Calibration','Background','Raw Data','Bin','Plot']

    calibButton = tk.Button(root,text = labels[0], width = 20, height = 5)
    bgButton = tk.Button(root,text = labels[1], width = 20, height = 5)
    rawButton = tk.Button(root,text = labels[2], width = 20, height = 5, state = 'disabled')
    binButton = tk.Button(root,text = labels[3], width = 20, height = 5, state = 'disabled')
    plotButton = tk.Button(text = labels[3], width = 40, height = 5, state = 'disabled')

    calibButton.grid(row = 0, column = 0)
    bgButton.grid(row=0,column=1)
    rawButton.grid(row=0,column=2)
    binButton.grid(row=1,column=0)
    plotButton.grid(row=1,column=1,columnspan = 2)

    bgButton.bind('<Button-1>', call_bgFrame)

    tk.mainloop()

注意:bgFrame() 函数是从 imaging 导入的函数之一,旨在 return 数组(使用 numpy)。

您的编码风格非常混乱。这个问题可以通过坚持更常见的编码风格来解决:将代码移到 __init__ 中,并将对小部件的引用保存为实例变量。

import Tkinter as tk
from imaging import *

class MainClass:
    def __init__(self):
        root = tk.Tk()
        root.title('Main Window')

        labels = ['Calibration','Background','Raw Data','Bin','Plot']

        self.calibButton = tk.Button(root,text = labels[0], width = 20, height = 5)
        self.bgButton = tk.Button(root,text = labels[1], width = 20, height = 5)
        self.rawButton = tk.Button(root,text = labels[2], width = 20, height = 5, state = 'disabled')
        self.binButton = tk.Button(root,text = labels[3], width = 20, height = 5, state = 'disabled')
        self.plotButton = tk.Button(text = labels[3], width = 40, height = 5, state = 'disabled')

        self.calibButton.grid(row = 0, column = 0)
        self.bgButton.grid(row=0,column=1)
        self.rawButton.grid(row=0,column=2)
        self.binButton.grid(row=1,column=0)
        self.plotButton.grid(row=1,column=1,columnspan = 2)

        self.bgButton.configure(command=self.call_bgFrame)

        root.mainloop()

    def call_bgFrame(self):    
        self.background = bgFrame()
        self.rawButton.config(state = 'normal')

app = MainClass()

还有其他一些我要更改的内容,但我尽量使您的代码与原始代码相似。