2013-10-18 71 views
0

我只是無法弄清楚這一個?如何用變量更改畫布上的字體?

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

似乎它應該很簡單,但我只是沒有得到它。感謝您的幫助。

回答

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

謝謝SOOOO多!我嘗試使用全局變量,但我害怕我過分複雜。再次謝謝你。 – user2866860

+0

@ user2866860,您可以通過[**接受答案**](http://meta.stackexchange.com/a/5235)表示感謝。 – falsetru

+0

爲什麼將rndfont設置爲StringVar,然後立即將其更改爲元組? –