Can';t更改按钮颜色,因为它没有定义-Python.Tkinter
尝试配置按钮,使其在单击后更改颜色Can';t更改按钮颜色,因为它没有定义-Python.Tkinter,python,python-3.x,tkinter,Python,Python 3.x,Tkinter,尝试配置按钮,使其在单击后更改颜色 from tkinter import * root = Tk() def buttonsMake(): for c in range(10): for r in range(3): movieSeats=Button(root, text="Empty", bg="green", fg="white", width=5, height=1, command=lambda c=c, r=r:[redCli
from tkinter import *
root = Tk()
def buttonsMake():
for c in range(10):
for r in range(3):
movieSeats=Button(root, text="Empty", bg="green", fg="white",
width=5, height=1, command=lambda c=c, r=r:[redClick(c, r)])
movieSeats.grid(row=r,column=c)
def redClick(c, r):
movieSeats.configure(bg="red")
buttonsMake()
root.mainloop()
我希望它会变色
以下是错误:
movieSeats=Button(root, text="Empty", bg="green", fg="white", width=5,
height=1, command=lambda c=c, r=r:[redClick(c, r)])
File "C:/Users/----/Downloads/test2.py", line 21, in redClick
movieSeats.configure(bg="red")
NameError: name 'movieSeats' is not defined
movieSeats
是buttonsMake()
中的局部变量,因此它在redClick
中不存在,您会得到错误未定义名称“movieSeats”
您必须在buttonsMake()
中使用global movieseat
来创建全局变量
顺便说一句: 将所有按钮分配给同一个变量,以便只能访问最后一个按钮。您可以保留列表中的所有按钮,也可以将其作为参数发送到
redClick
import tkinter as tk
# --- functions ---
def make_buttons():
for c in range(10):
for r in range(3):
btn = tk.Button(root, text="Empty")
btn['command'] = lambda c=c, r=r, b=btn:red_click(c, r, b)
btn.grid(row=r,column=c)
def red_click(c, r, btn):
btn.configure(bg="red")
# --- main ---
root = tk.Tk()
make_buttons()
root.mainloop()
使用按钮
{}
正确格式化代码。您不需要lambda中的列表-您可以执行lambda c=c,r=r:redClick(c,r)
movieSeats
在这两个函数中都是局部变量。您必须在buttonsMake()
中使用global movieSeats
来创建全局变量。顺便说一句:您将所有按钮分配给同一个变量,因此您只能访问最后一个按钮。你们必须在清单上保留按钮。或者将其作为参数发送到单击鼠标右键
。