如何使用变量更改画布上的字体?

时间:2013-10-18 13:12:04

标签: variables canvas fonts tkinter

我只是想不出这个?

from Tkinter import *

root=Tk()
rndfont=StringVar()

rndfont=("Purisa", 10)
def change():
   rndfont=("Purisa", 20, "bold")

canvas=Canvas(root, width=500, height=500)
canvas.pack()
canvas.create_text(50, 20, font=(rndfont), text="change")

button1 = Button(canvas, text = "change font", command = change, anchor = W)
button1.configure(width = 10, activebackground = "#33B5E5", relief = FLAT)
button1_window = canvas.create_window(50, 50, anchor=NW, window=button1)
root.mainloop()

似乎它应该很简单,但我只是没有得到它。感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

只需在函数内部分配rndfont即可创建一个局部变量;没有效果。

使用canvas.itemconfig更改字体。 (在此之前,您应该保存create_text)的返回值。

from Tkinter import *

root=Tk()

rndfont=("Purisa", 10)
def change():
   rndfont=("Purisa", 20, "bold") # --> Create local variable. Global varialbe does not change.
   canvas.itemconfig(text, font=rndfont) # <---

canvas=Canvas(root, width=500, height=500)
canvas.pack()
text = canvas.create_text(50, 20, font=(rndfont), text="change")
#^^^
button1 = Button(canvas, text = "change font", command = change, anchor = W)
button1.configure(width = 10, activebackground = "#33B5E5", relief = FLAT)
button1_window = canvas.create_window(50, 50, anchor=NW, window=button1)
root.mainloop()