Python3.4.1,Tkinter 8.6.3,类内事件在查找类按钮时引发“名称未定义”错误

2024-09-27 18:04:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在用户单击另一个按钮后将按钮的状态设置为“正常”,但不管出于什么原因,事件似乎找不到我引用的按钮,并抛出一个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导入的函数之一,用于返回数组(使用numpy)。在


Tags: textselflabelscolumnbuttonrootwidth按钮
1条回答
网友
1楼 · 发布于 2024-09-27 18:04:45

你的编码风格很混乱。这个问题可以通过坚持一种更常见的编码方式来解决:将代码移到__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()

还有一些其他的事情我会改变,但我尽量让你的代码与原始代码尽可能的相似。在

相关问题 更多 >

    热门问题