Tkinter 程序报错 ?
from tkinter import *
root=Tk()
root.geometry("344x233")
def gl(lg):
h.config(background=lg)
h=Button(root,
text="Tildebx",
width=26,height=6,
relief="groove",
borderwidth=9,
background="mediumseagreen",
command=gl("plum"))
h.pack(expand=True)
mainloop()
想法:点击按钮后,使其本身改变颜色
报错信息:h 未定义,怎么修改呀 ? 你好!你的代码报错是因为在创建按钮时,command=gl("plum") 这行代码会立即调用 gl 函数,而此时按钮变量 h 还未定义,导致“h 未定义”错误。
解决方案是将 command 参数改为一个 lambda 函数,这样只有在点击按钮时才会调用 gl 函数,此时 h 已经定义。
修改后的代码如下:
from tkinter import *
root = Tk()
root.geometry("344x233")
def gl(lg):
h.config(background=lg)
h = Button(root,
text="Tildebx",
width=26, height=6,
relief="groove",
borderwidth=9,
background="mediumseagreen",
command=lambda: gl("plum"))# 修改这里:使用 lambda 延迟调用
h.pack(expand=True)
mainloop()
这样修改后,点击按钮时,按钮本身的背景颜色就会变为 "plum"。如果还有其他问题,欢迎继续提问!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 from tkinter import *
root=Tk()
root.geometry("344x233")
def gl(): #修改gl函数,使其不需要参数
h.config(background="plum")
h=Button(root,
text="Tildebx",
width=26,height=6,
relief="groove",
borderwidth=9,
background="mediumseagreen",
command=gl)#直接传递函数引用
h.pack(expand=True)
mainloop() 记住!tkinter函数传参要用lambda,之前我提醒过你
from tkinter import *
root = Tk()
root.geometry("344x233")
def gl(lg):
h.config(background=lg)
h = Button(root,
text="Tildebx",
width=26, height=6,
relief="groove",
borderwidth=9,
background="mediumseagreen",
command=lambda: gl("plum"))# 修改这里:使用 lambda 延迟调用
h.pack(expand=True)
mainloop()
页:
[1]