[英]How to update colour variable outside of the function and update the window/canvas? (tkinter)
所以我正在尝试创建这个 pokeball 设计器。 我创建了一个开始时设置为“红色”的颜色变量,然后有一个按钮将绿色分配给颜色变量,尽管它似乎没有在 function 之外更新它并且它没有更新颜色window 中的形状。
那么我该如何更新 window 之外的颜色变量呢?
我如何让它在 canvas 上更新?
from tkinter import *
width = 500 # size of window is set
height = 500
colour = 'red' # colour is initially set to red
def colourchange():
colour = 'green'
window.update()
window = Tk() # creates window
canvas = Canvas(window, width=width, height=height) # creates canvas
canvas.create_arc(10, 10, width - 10, height - 10, fill=colour, style=PIESLICE, extent=180, width=10) # creates top shell of pokeball
canvas.create_arc(10, 10, width - 10, height - 10, fill='white', style=PIESLICE, extent=180, width=10, start=180) # creates bottom shell of pokeball
colourButton = Button(window, text='Switch Colour', command=colourchange) # creates button to switch colour of pokeball
colourButton.pack()
canvas.pack()
window.mainloop()
如果要更改颜色,则需要像创建它时那样配置它。 您不需要在此处使用update()
方法。 你可以做这样的事情。
from tkinter import *
width = 500 # size of window is set
height = 500
colour = 'red' # colour is initially set to red
def colourchange():
colour = 'green'
canvas.create_arc(10, 10, width - 10, height - 10, fill=colour, style=PIESLICE, extent=180, width=10)
window = Tk() # creates window
canvas = Canvas(window, width=width, height=height) # creates canvas
canvas.create_arc(10, 10, width - 10, height - 10, fill=colour, style=PIESLICE, extent=180, width=10) # creates top shell of pokeball
canvas.create_arc(10, 10, width - 10, height - 10, fill='white', style=PIESLICE, extent=180, width=10, start=180) # creates bottom shell of pokeball
colourButton = Button(window, text='Switch Colour', command=colourchange) # creates button to switch colour of pokeball
colourButton.pack()
canvas.pack()
window.mainloop()
您不能以这种方式在函数中更改全局变量colour
。 您的代码在 function 内创建了一个新的局部变量颜色。 如果要使用 function 更改颜色,请添加global
关键字
def colourchange():
global colour
colour = 'green'
window.update()
def colourchange():
global colour
colour = 'green'
window.update()
您需要使用 global 关键字来访问外部变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.