Python:切换按钮(添加更多按钮)

2024-06-02 05:18:00 发布

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

这只是按钮数组的初始代码,它们相互影响。我不明白为什么我不能理解这个定义!在

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()

我的定义错误在按钮1:

^{pr2}$

任何帮助都将不胜感激!在


Tags: fromimageimport定义tkintercolumnroot按钮
3条回答

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

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

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

在这一行

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

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

你想要这样的东西:

^{pr2}$

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

为了进一步阐述lambda,上面的语句或多或少是简写的

def temp_function():
    return changeImage(1)

button1 = Button(...,command=temp_function)

相关问题 更多 >