Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用tkinter更改按钮颜色_Python_Button_Tkinter - Fatal编程技术网

Python 如何使用tkinter更改按钮颜色

Python 如何使用tkinter更改按钮颜色,python,button,tkinter,Python,Button,Tkinter,我不断得到以下错误: AttributeError:“非类型”对象没有“配置”属性 # create color button self.button = Button(self, text = "Click Me", command = self.color_change, bg = "blue" ).grid(row = 2,

我不断得到以下错误: AttributeError:“非类型”对象没有“配置”属性

# create color button
self.button = Button(self,
                     text = "Click Me",
                     command = self.color_change,
                     bg = "blue"
                    ).grid(row = 2, column = 2, sticky = W)

def color_change(self):
    """Changes the button's color"""

    self.button.configure(bg = "red")

执行
self.button=button(…).grid(…)
时,分配给
self.button
的是
grid()
命令的结果,而不是对创建的
按钮的引用

在打包/网格化变量之前,需要分配
self.button
变量。 它应该是这样的:

self.button = Button(self,text="Click Me",command=self.color_change,bg="blue")
self.button.grid(row = 2, column = 2, sticky = W)

如果要在更改颜色的同时执行多个操作,另一种更改按钮颜色的方法。使用
Tk().after
方法并绑定一个change方法可以更改颜色并执行其他操作

Label.destroy
是after方法的另一个示例

    def export_win():
        //Some Operation
        orig_color = export_finding_graph.cget("background")
        export_finding_graph.configure(background = "green")

        tt = "Exported"
        label = Label(tab1_closed_observations, text=tt, font=("Helvetica", 12))
        label.grid(row=0,column=0,padx=10,pady=5,columnspan=3)

        def change(orig_color):
            export_finding_graph.configure(background = orig_color)

        tab1_closed_observations.after(1000, lambda: change(orig_color))
        tab1_closed_observations.after(500, label.destroy)


    export_finding_graph = Button(tab1_closed_observations, text='Export', command=export_win)
    export_finding_graph.grid(row=6,column=4,padx=70,pady=20,sticky='we',columnspan=3)

也可以还原为原始颜色

太好了,这就是解决办法!非常感谢!一旦你按下按钮,你会如何改变背景?@修辞鲁维姆请看我对你问题的回答。谢谢。只有bg=“red”也有效谢谢为什么否决票?