I have 2 function (Upload and Calc): 1st open file and writing its name (using button); 2nd should work with data from this file (excel file, will also start after button pressed). 1st part working well, but 2nd I dont understand how to get file name from 1st function(that getting file) to work in 2nd fuction(that work with data in file).
import tkinter as tk
from tkinter import Label, Pack, filedialog
from tkinter.constants import CENTER, LEFT
from tkinter.filedialog import askopenfilename
from pathlib import Path
from openpyxl import Workbook
import os
global filename
def Upload():
filename = filedialog.askopenfilename()
filepath=filename
path=Path(filepath)
#print(path.name)
#вставить проверку расширения файла
label2 = Label(text=path.name, font="Arial 17", justify=LEFT)
label2.place(relx=0.35, rely=.13)
#print('Selected:', filename)
return(path.name)
def Calc():
workbook = load_workbook(filename=path.name)
root= tk.Tk()
canvas1 = tk.Canvas(root, width = 300, height = 300)
canvas1.pack()
button1 = tk.Button(text='Open File',command=Upload, bg='purple',fg='white')
button1.place (relx = 0.5, rely = 0.5, anchor=CENTER)
button2 = tk.Button(text='Calculate',command=Calc, bg='purple',fg='white')
button2.place (relx = 0.5, rely = 0.6, anchor=CENTER)
label1 = Label(text= 'Выбраный файл:', fg="#eee", bg="#333")
label1.place(relx = 0.5, y=20, anchor=CENTER)
canvas1.create_window(150, 150, window=button1)
root.mainloop()
CodePudding user response:
Try making the variable path global:
def Upload():
global path
filename = filedialog.askopenfilename()
filepath=filename
path=Path(filepath)
#print(path.name)
#вставить проверку расширения файла
label2 = Label(text=path.name, font="Arial 17", justify=LEFT)
label2.place(relx=0.35, rely=.13)
#print('Selected:', filename)
return(path.name)
def Calc():
global path
workbook = load_workbook(filename=path.name)