programm should create a window, put a button in centr. when a button pressed opened a system window where a file need to be chosen, and after that, a file name should be written under the button. I got problems with the last part, file name displays only on console, tried to get filename
out of function, but I get an error.
import tkinter as tk
from tkinter import filedialog
from tkinter.constants import CENTER
from tkinter.filedialog import askopenfilename
def UploadAction(event=None):
filename = filedialog.askopenfilename()
print('Selected:', filename)
root= tk.Tk()
canvas1 = tk.Canvas(root, width = 300, height = 300)
canvas1.pack()
button1 = tk.Button(text='Click Me',command=UploadAction, bg='brown',fg='white')
canvas1.create_window(150, 150, window=button1)
button1.place (relx = 0.5, rely = 0.5, anchor=CENTER)
canvas1.create_text(relx = 0.5, rely = 0.7, anchor=CENTER, text= filename, fill="black", font=('Helvetica 15 bold'))
root.mainloop()
CodePudding user response:
It seems that you're trying to display text on a canvas, but there's an easier way using a label and changing its text:
import tkinter as tk
from tkinter.filedialog import askopenfilename
filename = None
def UploadAction(event=None):
filename = askopenfilename()
print('Selected:', filename)
# Change text of label
label1['text'] = filename
root= tk.Tk()
button1 = tk.Button(text='Click Me', command=UploadAction, bg='brown', fg='white')
button1.pack(padx=2, pady=5)
label1 = tk.Label(text='Please choose a file')
label1.pack(padx=2, pady=2)
root.mainloop()
If you want to display just the filename:
import tkinter as tk
from tkinter.filedialog import askopenfilename
filename = None
def UploadAction(event=None):
filename = askopenfilename()
# Cut path to the file off
filename = filename.split('/')[len(filename.split('/'))-1]
print('Selected:', filename)
label1['text'] = filename
root= tk.Tk()
button1 = tk.Button(text='Click Me', command=UploadAction, bg='brown', fg='white')
button1.pack(padx=2, pady=5)
label1 = tk.Label(text='Please choose a file')
label1.pack(padx=2, pady=2)
root.mainloop()