我正在努力解决这个问题。
说我有这样的代码:
def get_input(data_A, data_B):
all_data = [data_A.get(),dataB.get()]
return(all_data)
def the_gui():
root = Tk()
data_A = Entry(root)
data_B = Entry(root)
button = Button(root, text='Submit', command=lambda: get_input(data_A, data_B))
mainloop()
我的目标是在单击“提交”按钮后获取data_A和data_B的值。我尝试使用全局变量和其他所有方法,但一直未能抓住价值。
唯一有效的方法是将整个get_input()函数放入the_gui()函数中。但是,我认为这不是实施的好方法。
有什么建议?
这是一个简单的示例,说明如何编写此代码以获得所需的结果。
使用global时,所有的根窗口和相关字段都在一个函数中。因此,您必须在两个函数中都定义全局,这不是您想要执行的操作。
通常,您将要在全局名称空间中而不是在函数中写入根窗口,或者将其写入类中,这样就可以避免使用global。
button = Button(...)
可能没有按照您的想法去做。单击该命令后不会从命令返回值。Tkinter按钮不关心返回任何东西。因此,您必须在其他位置记录该值。
我不确定您的代码如何工作,因为您没有使用几何管理器,因此mainloop()
应该将其附加到根窗口,因此我也将其添加到其中。
范例1:
import tkinter as tk
def get_input():
global a_and_b
a_and_b = [data_a.get(), data_b.get()]
# If you want to keep a running record of all values submitted
# then you can do this instead:
# a_and_b.append([data_a.get(), data_b.get()])
def print_a_b():
print(a_and_b)
root = tk.Tk()
a_and_b = []
data_a = tk.Entry(root)
data_b = tk.Entry(root)
data_a.pack()
data_b.pack()
tk.Button(root, text='Submit', command=get_input).pack()
tk.Button(root, text='Print A/B List', command=print_a_b).pack()
root.mainloop()
示例2使用OOP:
import tkinter as tk
class App(tk.Tk):
def __init__(self):
super().__init__()
self.a_and_b = []
self.data_a = tk.Entry(self)
self.data_b = tk.Entry(self)
self.data_a.pack()
self.data_b.pack()
tk.Button(self, text='Submit', command=self.get_input).pack()
tk.Button(self, text='Print A/B List', command=self.print_a_b).pack()
def get_input(self):
self.a_and_b = [self.data_a.get(), self.data_b.get()]
def print_a_b(self):
print(self.a_and_b)
if __name__ == '__main__':
App().mainloop()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句