Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Can';t更改按钮颜色,因为它没有定义-Python.Tkinter_Python_Python 3.x_Tkinter - Fatal编程技术网

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
来创建全局变量。顺便说一句:您将所有按钮分配给同一个变量,因此您只能访问最后一个按钮。你们必须在清单上保留按钮。或者将其作为参数发送到
单击鼠标右键