首页 > 解决方案 > 如何在 tkinter GUI 中将函数返回值分配给类变量?

问题描述

我正在 Python3 中使用 tkinter 编写一个简单的 GUI。它允许用户按下一个调用函数的按钮select_files,让用户选择一堆文件。该函数处理文件并输出需要分配给类变量的三项元组,例如 a、b、c,以供进一步处理。我在类中定义的任何函数都应该可以访问这些变量。

我尝试了以下操作,但name 'self' is not defined出现错误。该函数select_files已经定义并编写在一个单独的 .py 文件中,我正在从正确的位置导入它。一般来说,我对 GUI 编程和面向对象的编程比较陌生。

我在这里研究了一个类似的问题:python tkinter return value from function used in command,这通常很有帮助,但无法帮助我解决我的具体问题。

这些self.a, self.b,self.c变量应该出现在__init__()方法下吗?如果是这样,我如何将它们分配给select_files函数的返回值?另外,这会使该功能变得open_files不必要吗?

from ... import select_files
import tkinter as tk
from tkinter import filedialog

class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.run_button()

    def open_files(self):
        self.a, self.b, self.c = select_files()

    print(self.a) #self is not defined error comes from here

    def run_button(self):
        self.button = tk.Button(root, text = 'run', command = self.open_files)
        self.button.pack()

if __name__ == "__main__":
    root = tk.Tk()
    MainApplication(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

编辑:根据 rassar 的评论,我进行了以下更改,并且它有效。用户可以按下打印按钮,对象被打印出来。有人现在可以解释为什么self.run_button()以及self.print_button()需要在 init 方法中吗?

class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.run_button()
        self.print_button()

    def open_files(self):
        self.a, self.b, self.c = select_files()

    def print_files(self):
        print(self.a)

    def run_button(self):
        self.button = tk.Button(root, text = 'run', command = self.open_files)
        self.button.pack()

    def print_button(self):
        self.button = tk.Button(root, text = 'print', command = self.print_files)
        self.button.pack()

if __name__ == "__main__":
    root = tk.Tk()
    MainApplication(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

标签: pythonpython-3.xtkinter

解决方案


推荐阅读