0

我正在尝试从一个函数上传 zip 文件,并通过从另一个函数获取变量中的路径来提取该文件,但无法获得解决方案。下面是我的用户界面的代码,附件是 UI 链接。

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()

[用户界面链接][1] [1]:https://i.stack.imgur.com/57EZ2.png

4

1 回答 1

0

一种方法是在input_path里面声明为全局变量UploadAction(),然后就可以在里面访问了extraction()

请注意,最好使用askopenfilename()而不是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()

更好的方法是使用类和实例变量:

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()
于 2022-01-27T08:52:24.007 回答