更改函数中Tkinter按钮的颜色

2024-10-03 00:18:43 发布

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

我想在按另一个按钮时改变按钮的颜色。下面的代码重新创建属性错误。在

理想情况下,解决方案应该能够更改按钮的所有属性(请参阅尝试的状态更改),但我没有将此添加到标题中,因为我不知道“属性”是否是正确的单词。在

import Tkinter

def tester():

    class window(Tkinter.Tk):
        def __init__(self,parent):
            Tkinter.Tk.__init__(self,parent)
            self.parent = parent
            self.initialize()

        def initialize(self):
            self.grid()
            button1 = Tkinter.Button(self,text=u"Button")
            button1.grid(padx=5,pady=5)

            button2 = Tkinter.Button(self,text=u"Change",command=self.colourer)
            button2.grid(column=1,row=0,pady=5)  

            button3 = Tkinter.Button(self,text=u"Disabled",state='disabled')
            button3.grid(column=1,row=0,pady=5)                     

        def colourer(self):
            self.button1.configure(bg='red')
#           self.button1.config(bg='red')  -- this gives same error
#           self.button3.configure(state='normal')  -- as does this
    if __name__ == "__main__":
        app = window(None)
        app.title('Tester')
        app.mainloop()

tester()

这里建议的所有方法都会产生相同的错误:Changing colour of buttons in tkinter

谢谢


Tags: textselfapp属性tkinterdef错误button
2条回答
  1. 你需要给self.button1,而declaring
  2. 若您看到网格,您为button2和button 3指定了相同的列名,以便它们彼此重叠

试试这个

import Tkinter

def tester():

    class window(Tkinter.Tk):
        def __init__(self,parent):
            Tkinter.Tk.__init__(self,parent)
            self.parent = parent
            self.initialize()

        def initialize(self):
            print self.grid()
            self.button1 = Tkinter.Button(self,text=u"Button")
            self.button1.grid(padx=5,pady=5)

            self.button2 = Tkinter.Button(self,text=u"Change",command=self.colourer)
            self.button2.grid(column=1,row=0,pady=5)

            self.button3 = Tkinter.Button(self,text=u"Disabled",state='disabled')
            self.button3.grid(column=2,row=0,pady=5)



        def colourer(self):
            self.button1.configure(bg='red')
#           self.button1.config(bg='red')    this gives same error
#           self.button3.configure(state='normal')    as does this
    if __name__ == "__main__":
        app = window(None)
        app.title('Tester')
        app.mainloop()

tester()

问题的根源是没有定义self.button。您需要为该变量赋值:

self.button = Tkinter.Button(...)

相关问题 更多 >