2013-03-29 37 views
0

我想通過單選按鈕更新TopLevel小部件的背景顏色。 我想要的是當用戶改變單選按鈕時背景顏色會改變。 目前,該程序打開一個新窗口,單選按鈕。背景顏色根本不會改變。更新Toplevel小部件中的背景顏色

from tkinter import * 

class Example: 

    def newWindow(self): 
     top = Toplevel() 
     v = IntVar() 
     v.set(-1) 
     self.aRadioButton = Radiobutton(top, text="Blue",variable = v, value = 0) 
     self.aRadioButton.grid(row=1, column=1) 
     self.aRadioButton = Radiobutton(top, text="Red",variable = v, value = 1) 
     self.aRadioButton.grid(row=1, column=0) 

     if v == 0: 
      top.configure(bg="Blue") 
     elif v == 1: 
      top.configure(bg="Red") 


    def __init__(self, master): 
     frame = Frame(master, width = 50, height = 50) 
     frame.grid() 

     self.aLabel = Label(frame, text = "New window bg colour").grid(row=0) 

     self.aButton = Button(frame, text="To new window", command=self.newWindow) 
     self.aButton.grid(row=1) 

root = Tk() 
app = Example(root) 
root.mainloop() 
+0

必須有某種事件,當您更改單選按鈕時......應該改變顏色。 'newWindow'只被調用一次。 – davekr

回答

1

當您更改單選按鈕時,您必須使用事件。 附加命令的方法是這樣的單選按鈕:

self.aRadioButton = Radiobutton(top, text="Blue",variable = v, value = 0, command=lambda: top.configure(bg="Blue")) 
self.aRadioButton = Radiobutton(top, text="Red",variable = v, value = 1, command=lambda: top.configure(bg="Red")) 

此外,當你這樣做,你不需要變量v,如果你用它僅適用於該purpouse。

+0

非常感謝,現在完美工作:) – Student