如何在Tkinter中更新按钮上的图像?

问题描述

当我单击“ apply_but”按钮时,我希望更新此按钮上的图片。但这是行不通的。 另一个问题是,当我打开该窗口时,“噪声插入”方法“ curves”也起作用,并打开另一个带有标签“您在寻找什么”的窗口。但是,只有在单击“ img_but”按钮后,此方法才有效。

class Noise(Toplevel):
    def __init__(self,pic):
        super().__init__()

        w = self.winfo_screenwidth() // 2 - 300  # ширина экрана
        h = self.winfo_screenheight() // 2 - 300  # высота экрана

        self.geometry('600x600+{}+{}'.format(w,h))

        self.title('Noise insertion')
        self.resizable(width=False,height=False)
        self['bg'] = '#7be8cf'

        Label(self,text='Noise insertion',font=('Comic Sans MS',20),fg='#3d3d42',bg='#7be8cf').place(x=200,y=0)

        var = Intvar()
        var.set(0)
        var2 = Intvar()
        var2.set(0)

        self.yes_but = Radiobutton(self,text="Yes",variable=var,value=0,width='10',height='1',activebackground='#e6f547',bg='#7be8cf')
        self.no_but = Radiobutton(self,text="No",value=1,bg='#7be8cf')
        self.salt_but = Radiobutton(self,text="salt and peper",variable=var2,bg='#7be8cf')
        self.gauss_but = Radiobutton(self,text="gauss noise",bg='#7be8cf')
        self.scale = Scale(self,orient=VERTICAL,from_=0,to=100,bg='#7be8cf',font='10',highlightbackground='#7be8cf',label='%',fg='#f53be2')
        self.apply_but = Button(self,text='Apply',10),width='15',bg='grey',fg='white',bd=20,command=self.update_pic(pic))

        self.img_but = Button(self,image=pic,command = self.curves())

        # Pack()
        self.yes_but.place(x=0,y=100)
        self.no_but.place(x=0,y=50)
        self.salt_but.place(x=220,y=50)
        self.gauss_but.place(x=220,y=100)
        self.scale.place(x=500,y=50)
        self.apply_but.place(x=220,y=200)
        self.img_but.place(x=150,y=300)

    def update_pic(self,pic):
        var = self.scale.get()
        scale_res = self.scale.get()
        self.img = ImageTk.PhotoImage(get_pic('color_dragon.jpg',size= 
                              (300,200)).filter(ImageFilter.GaussianBlur))
        #self.img_but[image] = self.img ???

        pass

    def curves(self):
        Curves()
        pass

class Curves(Toplevel):
    def __init__(self):
        super().__init__()
        w = self.winfo_screenwidth() // 2 - 300  # ширина экрана
        h = self.winfo_screenheight() // 2 - 300  # высота экрана

        self.geometry('600x600+{}+{}'.format(w,h))

        self.title('Curves')
        self.resizable(width=False,text='What are u looking for?',bg='#7be8cf').pack()

解决方法

命令不应直接调用函数-相反,它们应在激活时命名要调用的函数。

尝试替换为:command=self.update_pic(pic)

与此:command = lambda pic=pic: self.update_pic(pic)

这是command = self.curves()

为此:command = self.curves