我想在点击时从每个新生成的文本/条目小部件中获取数据:
for i in range(len(list1)):
tk.Text(frame, height=1, width = 30).grid(row=i+3, column=2, sticky ='w',
padx = 10, pady = 4)
答案 0 :(得分:0)
这是四个问题的组合:
如何在条目中获取字符串?
import tkinter as tk
...
entry = tk.Entry(...)
...
entry.get() # gets the string in an Entry
如何在文字中获取字符串?
import tkinter as tk
...
text = tk.Text(...)
...
text.get('1.0', 'end-1c')
如何在点击小部件时调用方法?
import tkinter as tk
...
def a_method(*args):
print("Hello")
...
widget = tk.Label(...)
...
widget.bind('<Button-1>', a_method)
如何动态创建小部件?
动态创建小部件并不是不将它们分配给变量的借口。将这些特定对象分配给变量并不是绝对必要的,但我怀疑这是python程序员想要处理的内容。
使用可迭代类型创建多个小部件,例如dict
:
import tkinter as tk
...
a_dict = dict()
my_widget_names = {"Township", "Rebellion", "Know", ...}
for name in my_widget_names:
a_dict[name] = tk.Button(...)
这是一个包含以上所有内容的示例:
try: # In order to be able to import tkinter for
import tkinter as tk # either in python 2 or in python 3
except ImportError:
import Tkinter as tk
def display_data(d, key):
if d[key].winfo_class() == 'Text':
data = d[key].get('1.0', 'end-1c')
elif d[key].winfo_class() == 'Entry':
data = d[key].get()
print(data)
def populate_widgets(widget_class_name, keys):
global root
widget_dict = dict()
if widget_class_name in ('Text', 'Entry'):
if widget_class_name == 'Text':
for name in keys:
widget_dict[name] = tk.Text(root, height=4)
elif widget_class_name == 'Entry':
for name in keys:
widget_dict[name] = tk.Entry(root)
for name in keys:
widget_dict[name].pack()
widget_dict[name].bind('<Button-1>',
lambda event, d=widget_dict,
key=name: display_data(d, key))
return widget_dict
if __name__ == '__main__':
root = tk.Tk()
widget_names = {"Township", "Rebellion", "Know", "Your", "Enemy"}
my_text_widgets = populate_widgets('Text', widget_names)
my_entry_widgets = populate_widgets('Entry', widget_names)
root.mainloop()