Python 3 PhotoImage 在渲染多次时跨标签重复

标签 python tkinter

我有一个 Python 3 Tkinter 程序,该程序应该从特殊文件格式渲染图像。

from tkinter import *

image = []

path = Tk()
display = Toplevel()

display.wm_title("RCSVvisual")
display.wm_iconbitmap("favicon.ico")

path.wm_title("RCSVpath")
path.wm_iconbitmap("favicon.ico")

entry1 = Entry(path)
entry1.pack(side=LEFT)

photo = PhotoImage(width=240, height=180)

def refresh():
    file_path = entry1.get()
    with open(file_path, "r") as file:
        for line in file:
            thisLine = line.strip()
            thisArray = thisLine.split(",")
            image.append(thisArray)

    for c1 in range(0, len(image)):
        for c2 in range(0, len(image[c1])):
            photo.put(image[c1][c2], (c1, c2))

button = Button(path, text="Open File", command=refresh)
button.pack(side=LEFT)

label = Label(display, image=photo)
label.pack()

path.mainloop()
display.mainloop()

这是我测试的文件:

#F00,#0F0,#00F,#F00
#0F0,#00F,#F00,#0F0
#00F,#F00,#0F0,#00F
#F00,#0F0,#00F,#F00

但是,如果您多次运行该程序,该镜像似乎不会替换旧的镜像;而不是显示在原始图像的右侧。我在这里做错了什么吗?我应该再次 .pack() 目标标签吗?

最佳答案

您总是附加到图像

如果要创建新图像,应先清空现有列表。

def refresh():
    image = []
    file_path = entry1.get()
    ....

此外,几乎总是您的程序中只需要一个主循环。您应该删除 display.mainloop() 行。

关于Python 3 PhotoImage 在渲染多次时跨标签重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42851044/

相关文章:

python - Django 日期格式交换

python - Tkinter 应用程序中的日期更改通知 (win32)

python - 是否可以使用 Tkinter 条目作为输入,通过按钮触发器将值传递到信号生成器?

python - 为什么这两行代码不会产生相同的结果?

python - 如何在 Qiskit python 中调用 EnergyInput() 函数?

python - 在 Django 中更改模型会导致数据库损坏?

python - 属性错误: module 'urllib3' has no attribute 'urlopen' in python

python - 如何在不重复代码的情况下定义 randint 的元组?

python - Tkinter 网格不工作

python - 以编程方式按下工具栏上的 `X` 按钮?