python - 如何在 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()
解决方案
推荐阅读
- c++ - 带有向量的 C++ 魔术 8 球
- python - 为什么我的 return 语句没有显示任何输出?
- python-3.x - NameError:名称“子弹”未定义
- r - 为什么一个 R 函数包含大约。400行代码有633Kb?
- javascript - 在 javascript+flow 中,将 ?string 发送到需要字符串的函数中
- html - 用于跟随兄弟节点和自身节点的 XPath?
- python - Flask、Marshmallow 3 和 webargs use_args 无法解析参数
- python - 从用户那里获取两个数据的烧瓶 Web 应用程序只接受一个字段中的数据
- python - 在 pythone 中打印孟加拉语
- python - 如何使python检查dict重复键而不是静默删除