Сначала вы должны вызвать функцию excel
. Во-вторых, аргумент askopenfilename
должен быть filetypes
, а не filetype
.
import os
import tkinter as tk
from tkinter import filedialog
def excel():
global variable
try:
filename = filedialog.askopenfilename(
title="Add a file",
filetypes=[("Excel", "*.xlsx")]
)
except FileNotFoundError:
filename = ""
if filename:
variable = os.path.basename(filename)
def print_global_variable():
global variable
print(variable)
def main():
global variable
root = tk.Tk()
variable = ""
button_1 = tk.Button(root, text="Click", command=excel)
button_1.pack()
button_2 = tk.Button(
root,
text="Print Variable",
command=print_global_variable
)
button_2.pack()
root.mainloop()
main()
. Или вот версия класса:
import os
import tkinter as tk
from tkinter import filedialog
class App(tk.Frame):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.pack()
self.variable = ""
self.button_1 = tk.Button(
self, text="Click", command=self.excel
)
self.button_1.pack()
self.button_2 = tk.Button(
self,
text="Print Variable",
command=lambda: print(self.variable)
)
self.button_2.pack()
def excel(self):
try:
filename = filedialog.askopenfilename(
title="Add a file",
filetypes=[("Excel", "*.xlsx")]
)
except FileNotFoundError:
filename = ""
if filename:
self.variable = os.path.basename(filename)
App(master=tk.Tk()).mainloop()