我做了一个简单的游戏,开始学习python,按下按钮,颜色就会改变。我尝试执行此操作,但是即使变量更改,它也不会更改颜色。我知道这有点混乱,但我仍在学习。
我已经整理了一些代码
from random import randint
from tkinter import *
color_numb = randint(1,3)
status = True
color = "Blue"
root = Tk()
if True:
if color_numb == 1:
color = "Blue"
if color_numb == 2:
color = "Orange"
if color_numb == 3:
color = "Red"
T = Text(root, height=2, width=30, fg=color)
def ColorC():
color_numb = randint(1,3)
if color_numb == 1:
color = "Blue"
if color_numb == 2:
color = "Orange"
if color_numb == 3:
color = "Red"
T.delete(0.0, END)
T.insert (END, (color))
print((color_numb), (color))
buttonA = Button(root, text = 'Change the colour!', command=ColorC)
T.pack()
buttonA.pack()
答案 0 :(得分:2)
代码的问题是您实际上并未更改文本小部件的颜色。您只需设置颜色一次:
T = Text(root, height=2, width=30, fg=color)
然后,当您单击颜色时,您尝试更改颜色(尽管您只修改了 local color
变量,而不是全局变量),但实际上从未更新文本小部件的颜色。
要更改小部件的颜色,您需要使用configure
重新配置它:
# reconfigure widget color
T.configure(foreground=color)
# delete existing text
T.delete(0.0, END)
# set new text
T.insert(END, color)