大多数时候,回调会删除返回值(所有tkinter
回调做),如果有的话。这是因为使用最常用于回调的观察者模式来管理返回值有点尴尬。
将值从 CB 转移到需要的地方有两种主要方法:
一种是使用container object
- 这可能是一个简单的Pythonlist
or dict
,或更详细的data class
可以通过callback
,并进行变异以为其分配正确的值。
这是一个使用字典的非常简单的例子:
import tkinter as tk
def print_info():
print(f'from print_info: {information_transfer}')
def submit():
information_transfer['name'] = name_entry.get()
print(f'after input: {information_transfer}')
root=tk.Tk()
root.geometry("600x400")
name_label = tk.Label(root, text = 'Username', font=('calibre', 10, 'bold'))
name_entry = tk.Entry(root, font=('calibre', 10, 'normal'))
sub_btn = tk.Button(root,text='Submit', command=submit)
info_btn = tk.Button(root,text='print info', command=print_info)
name_label.grid(row=0, column=0)
name_entry.grid(row=0, column=1)
sub_btn.grid(row=2, column=1)
info_btn.grid(row=3, column=1)
information_transfer = {'name': None, 'other': None}
print(f'before input: {information_transfer}')
root.mainloop()
另一个是 @DavidGildour 在另一个答案中描述的 OOP 方法。