简体   繁体   English

无法更改按钮颜色,因为未定义-Python .Tkinter

[英]Can't change button color because it is not defined - Python .Tkinter

trying to configure button so that it changes color once clicked. 尝试配置按钮,以便单击后更改颜色。

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

I expect it to change color Here's the error: 我希望它会改变颜色这是错误:

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 is local variable in buttonsMake() so it doesn't exist in redClick and you get error name 'movieSeats' is not defined movieSeats是局部变量buttonsMake()因此不存在在redClick ,你会得到错误name 'movieSeats' is not defined

You have to use global movieSeats in buttonsMake() to create global variable. 您必须在buttonsMake()使用global movieSeats才能创建全局变量。


BTW: BTW:

You assing all buttons to the same variable so you have access only to last button. 您将所有按钮都关联到同一变量,因此您只能访问最后一个按钮。 You can keep all buttons on list or send it to redClick as parameter 您可以将所有按钮保留在列表中或将其发送给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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM