I have been trying to make a tk button which locates a file and prints the filename on the tk window as a Label. What I also want it to do is to update the Label with the new filename if the button would be pressed again . However, all it does now is print a new Label with the new filename under the previous Label, so I suppose that the only thing that isn't working in my code is .destroy()
. Here is the function which is the command for the button as it is now:
from tkinter import *
from tkinter import filedialog
import os
import getpass
user = getpass.getuser()
cntr5 = 0
def open1():
global cntr5
global file1
file1 = filedialog.askopenfilename(initialdir = "C:/Users/%s" % user, title = "Select a file", filetypes = ((".dbc files", "*.dbc"),))
p1 = Label(screen, text = "File 1:")
pa1 = Label(screen, text = os.path.split(str(file1)[2:])[1], fg = "dark green")
if file1 != "" and cntr5 == 0:
p1.pack()
pa1.pack()
cntr5 += 1
elif file1 != "" and cntr5 != 0:
pa1.destroy()
pa1 = Label(screen, text = os.path.split(str(file1)[2:])[1], fg = "dark green")
pa1.pack()
else:
pass
I've also tried to use pa1.configure()
within elif:
but that won't do the trick either. Please help with this.
I solved it! This is how:
from tkinter import filedialog
import os
import getpass
user = getpass.getuser()
cntr5 = 0
def open1():
global cntr5
global file1
global p1
global pa1
file1 = filedialog.askopenfilename(initialdir = "C:/Users/%s" % user, title = "Select a file", filetypes = ((".dbc files", "*.dbc"),))
if file1 != "" and cntr5 == 0:
p1.pack()
pa1.configure(text = os.path.split(str(file1)[2:])[1])
pa1.pack()
cntr5 += 1
elif file1 != "" and cntr5 != 0:
p1.destroy()
pa1.destroy()
p1 = Label(screen, text = "File 1:")
pa1 = Label(screen, text = os.path.split(str(file1)[2:])[1], fg = "dark green")
p1.pack()
pa1.pack()
else:
pass
p1 = Label(screen, text = "File 1:")
pa1 = Label(screen, text = "hi", fg = "dark green")
Thank you to @acw1668
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.