0

这只是按钮数组的初始代码,它们相互影响。我无法理解为什么我不断收到这个定义错误!

from tkinter import *
import tkinter.messagebox
from tkinter import ttk


def changeImage(Num):
    global buttonOn
    global buttonOff
    if Num == 1:
        if button1(image) == buttonOn:
            button1.config(image=buttonOff)
        else:
            button1.config(image=buttonOn)

root = Tk()

root.geometry('155x190')
root.title("Tile Turner")

buttonOn = PhotoImage(file="buttonPic.gif")
buttonOff = PhotoImage(file="buttonPic2.gif")

button1 = Button(image=buttonOn, width=20, height=20, command=changeImage(1))
buttonQuit = Button(text="Quit", width=10, height=0, command=root.destroy)


app.grid(column=0, row=0)
button1.grid(column=2, row = 3)
buttonQuit.grid(column=3, row = 10, columnspan = 4)

root.mainloop()

我的定义错误在 button1 中:

Traceback (most recent call last):
  File "C:/Users/Jimmy/Desktop/COS 2013/Game1/small", line 23, in <module>
    button1 = Button(image=buttonOn, width=20, height=20, command=changeImage(1))
  File "C:/Users/Jimmy/Desktop/COS 2013/Game1/small", line 10, in changeImage
    if button1(image) == buttonOn:
NameError: global name 'button1' is not defined

任何帮助将不胜感激!

4

3 回答 3

1

在这一行中,

button1 = Button(image=buttonOn, width=20, height=20, command=changeImage(1))

您调用作为参数changeImage传入1的函数。然后对该函数进行评估,并将结果None在本例中)传递给构造函数的command=...默认参数Button。当然,这会导致您得到 ,NameError因为您changeImage在实际将其传递给 Button 构造函数之前调用了它——即button1还不存在,因为它正在等待changeImage函数完成,然后才能继续构造Button实例。

你想要这样的东西:

button1 = Button(...,command=lambda:changeImage(1))

这将创建一个新函数,调用该函数时只需changeImage使用正确的参数调用。

为了进一步详细说明 lambda,上面的语句或多或少是

def temp_function():
    return changeImage(1)

button1 = Button(...,command=temp_function)
于 2013-03-01T02:48:40.683 回答
0

尝试button1在您的def changeImage(Num). Python 是自上而下读取的,因此即使没有调用该函数,您也应该在到达该点之前声明所有内容。

于 2013-03-01T02:39:12.097 回答
0

您需要保留对图像的引用,以便可以在事件处理程序中切换它:

def changeImage(num):
    global buttonOn, buttonOff, button1
    if num == 1:
        newimage = buttonOff if button1.image == buttonOn else buttonOn
        button1.image = newimage
        button1.config(image=newimage)

# ...
button1 = Button(image=buttonOn, width=20, height=20, command=lambda:changeImage(1))
button1.image = buttonOn
于 2013-03-01T02:56:25.450 回答