更新顶级widg中的背景颜色

2024-10-01 22:34:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过一个单选按钮来更新顶层小部件的背景色。 我想要的是当用户更改单选按钮时背景颜色会发生变化。 目前,该程序将打开一个新窗口,其中有一个单选按钮。背景色一点也不改变。在

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

Tags: textselfexampletopdefroot按钮frame
1条回答
网友
1楼 · 发布于 2024-10-01 22:34:21

更改单选按钮时,必须使用事件。 将命令方法附加到单选按钮,如下所示:

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

同样,当您这样做时,如果您只为这个purpouse使用变量v,则不需要它。在

相关问题 更多 >

    热门问题