访问函数外部变量我使用另一种方法,但不起作用

2024-04-25 10:02:05 发布

您现在位置:Python中文网/ 问答频道 /正文

这个项目是由特金特建造的

我想访问函数外部的路径变量:

这是我的代码:

excelName = None

def excel():

    global excelName
    filename = filedialog.askopenfilename(title="Add a file", filetype=(("Excel", "*.xlsx")))

    path = filename
    excelName = os.path.basename(path) # This is Variable 

print(excelName) # This variable need to access from excel() function

结果是:

C:\Python\python.exe C:\PycharmProjects\Test\excel.py

None

Process finished with exit code 0

Tags: path项目函数代码路径nonetitledef
1条回答
网友
1楼 · 发布于 2024-04-25 10:02:05

首先,您应该调用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()

相关问题 更多 >

    热门问题