首页 > 解决方案 > 带有标签的 tkinter 破坏方法存在问题

问题描述

第一次在 Stack 上发帖!我对 Python / Tkinter 很陌生,所以请耐心等待。

我正在尝试编写代码,在启动时查找保存的 txt 文件,该文件描述了所选 XML 文件的路径,并根据所选目录打印 tkinter 标签。

我遇到的问题是:如果您选择 XML 文件路径,它将打印路径 - 这就是我想要的。但是,如果您选择另一个 XML 文件路径,之前打印的标签不会被破坏,并且新标签会应用到旧标签之上。我看过其他有类似问题的人,我被困住了。我尝试了几种不同的方法来实现该.destroy()方法,但似乎都没有奏效。如果我的代码中存在其他错误/冗余(请关注这个.destroy()问题) ,我不会感到惊讶,但它似乎以我想要的方式工作,而不是这个问题。我没有收到此代码的任何错误消息。

这是代码现在的样子(我只发布了有问题的部分,如果您需要更多,请告诉我)。

我一直在通过先选择一个长文件路径,然后在桌面上选择一个较短的路径来测试这个问题。桌面上的路径将打印在前一个标签的顶部,而不是破坏前一个标签,似乎忽略了 reset() 函数。

import xml.etree.ElementTree as ET 
from tkinter import filedialog
from tkinter import *
import tkinter as tk

root= tk.Tk() 
 
canvas1 = tk.Canvas(root, width = 750, height = 750)
canvas1.pack()

#Destroy previous label
global label_file
def reset():
    label_file.destroy()

#Function that saves selected path
def findfile():
    reset()
    global file_selected
    file_selected = filedialog.askopenfilename(filetypes=[("XML Files", "*.xml")])
    if file_selected == "":
        label_file = tk.Label(root, text= 'Error. Choose location of config.xml:', bg='red' )
        canvas1.create_window(370, 165, window=label_file)
    else:
        label_file = tk.Label(root, text= 'Saved Path: '+ file_selected, bg='yellow' )
        canvas1.create_window(370, 165, window=label_file)
        savedpath = open("path.txt", "w")
        savedpath.write(file_selected)
        
#Attempts to read save file on startup
try:
    with open('path.txt', 'r') as f:
        global file_selected
        file_selected = f.readline()   
        label_file = tk.Label(root, text= 'Path: ' + file_selected, bg='#00ff00' )
        canvas1.create_window(370, 165, window=label_file)
        button1 = tk.Button (root, text='Change Path',command=findfile, bg='orange')
        canvas1.create_window(50, 200, window=button1)
        
#If no save file on startup
except FileNotFoundError:
    file_selected = ""
    label_file = tk.Label(root, text= 'Choose location of config.xml file: ', bg='red' )
    canvas1.create_window(168, 165, window=label_file)
    button2 = tk.Button (root, text='Browse',command=findfile, bg='orange') 
    canvas1.create_window(50, 200, window=button2) 

root.mainloop()

标签: pythontkinter

解决方案


推荐阅读