如何修复change()函数中重复的root.mainloop()调用?我想通过更改滚动条来更改图像

2024-04-25 08:04:45 发布

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

有10个滑块,每个滑块值都会更改窗口中的图像。但是如果不在change()函数中调用root.mainloop(),我找不到一种方法来实现这一点。这最终导致堆栈溢出,我通过打印回溯长度('memory'变量)检查了这一点

root = tk.Tk()

class SliderClass:
    def __init__(self,i,j):
        global no
        self.no = no
        self.w = Scale(root, label="PCA_feature "+str(self.no+1), 
            from_=10, to=-10, tickinterval=0.1, orient=HORIZONTAL, showvalue=0)
        self.w.grid(row=i,column=j)
        self.w.bind("<ButtonRelease-1>", self.change)
        self.w.set(np.clip(z[self.no],-10.0,10.0))
        no +=1

    def change(self, event):
        memory = ''.join(traceback.format_stack())
        print(len(memory))
        z[self.no] = self.w.get()
        z_inv = pca.inverse_transform(z).reshape((1,-1))
        im = G.layers[2].predict(z_inv)
        im = (0.5 * im + 0.5)*255
        im = im[0,:,:,:].astype('uint8')
        im = cv2.resize(im,(150,150))
        im = Image.fromarray(im)
        im = PhotoImage(im)
        panel.configure(image=im)
        root.mainloop()

im = Image.fromarray(im)
im = PhotoImage(im)
panel = Label(root, image = im, width=300,height=300)
panel.grid(rowspan=2,column=0)

r,c = 2,5
for i in range(r):
    for j in range(1,c+1):
        s = SliderClass(i,j)
        sliders.append(s)

root.mainloop()

Tags: noimageselfdefcolumnrootchangegrid
1条回答
网友
1楼 · 发布于 2024-04-25 08:04:45

您不需要在函数中调用mainloop。在程序的生命周期中,应该只调用一次

当您删除对mainloop的调用时,映像不会显示,这是因为您没有存储对映像的引用,所以当函数超出范围时,它会被垃圾收集器删除。通过在函数中运行mainloop,您可以防止这种情况发生,但会导致更严重的问题(即您正在撰写的问题)

除了删除函数中对mainloop的调用外,还需要保存对图像对象的引用。一个简单的改变是使用像self.im这样的属性,而不是局部变量im

相关问题 更多 >