'I want to upload a file and extract it using python tkinter button but getting error in it
I am trying to upload the zip file from one function and extract that file by getting the path in a variable from another function but couldn't get the solution. below is the code of my user-interface and attach is the UI link.
from tkinter import *
from zipfile import ZipFile
import tkinter.filedialog as filedialog
def UploadAction():
input_path = filedialog.askopenfile(filetypes=[('Zip file', '*.zip')])
# I want to get this (input_path) value and pass to extraction function to extract the file
def extraction():
john = ZipFile('', 'r')
john.extractall('C:/Users/anjum/Downloads/New folder')
john.close()
w2 = Tk()
w2.geometry("1366x768")
uplaod_button = Button(w2, bg="gray", fg="white", text='Upload zip file', width=30, font
("bold", 12), command=UploadAction)
uplaod_button.place(x=600, y=120)
extract = Button(w2, bg="gray", fg="white", text='Extract zip file', font=("bold", 12), width=25, command=extraction)
extract.place(x=620, y=175)
w2.mainloop()
[User Interface link][1] [1]: https://i.stack.imgur.com/57EZ2.png
Solution 1:[1]
One of the way is to declare input_path as global variable inside UploadAction(), then it can be accessed inside extraction().
Note that it is better to use askopenfilename() instead of askopenfile().
input_path = None
def UploadAction():
global input_path
input_path = filedialog.askopenfilename(filetypes=[('Zip file', '*.zip')])
# I want to get this (input_path) value and pass to extraction function to extract the file
def extraction():
if input_path:
john = ZipFile(input_path, 'r')
john.extractall('C:/Users/anjum/Downloads/New folder')
john.close()
Better way is to use class and instance variable:
import tkinter as tk
from tkinter import filedialog
from zipfile import ZipFile
class App(tk.Tk):
def __init__(self):
super().__init__()
self.geometry('1366x768')
self.input_path = None
uplaod_button = tk.Button(self, bg="gray", fg="white", text='Upload zip file',
width=30, font=("bold", 12), command=self.UploadAction)
uplaod_button.place(x=600, y=120)
extract = tk.Button(self, bg="gray", fg="white", text='Extract zip file',
font=("bold", 12), width=25, command=self.extraction)
extract.place(x=620, y=175)
def UploadAction(self):
self.input_path = filedialog.askopenfilename(filetypes=[('Zip file', '*.zip')])
def extraction(self):
if self.input_path:
with ZipFile(self.input_path, 'r') as john:
john.extractall('C:/Users/anjum/Downloads/New folder')
App().mainloop()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
