tkinter
我使用该库在 Python 中制作了一个 UI 。不幸的是,我不知道如何在不使用按钮的情况下从tk.Text
或小部件获取用户输入。tk.Listbox
我正在尝试将用户输入分配给一个变量,该变量在 root.destroy
使用按钮调用或手动关闭 UI 时立即采用永久值。这适用于小部件,例如tk.Entry
或tk.Radiobutton
。我想知道我怎样才能让它也适用于tk.Text
小tk.Listbox
部件。下面显示了一个示例代码,希望它能清楚地说明我想要做什么。
# Import tkinter library
import tkinter as tk
import tkinter.ttk as ttk
# Function to create root
def CreateRoot(Pos, Dim, Color, Text):
Root = tk.Tk()
Root.config(width = Pos[0])
Root.config(height = Pos[1])
Root.geometry(str(Dim[0]) + 'x' + str(Dim[1]))
Root.config(bg = Color)
Root.title(Text)
return Root
# Function to add entry to root
# that allows one element
# from some given list 'Val'
def CombEntry(Root, Pos, Dim, Style, Var, Val):
Entry = ttk.Combobox(Root)
Entry.place(x = 1000 * Pos[0])
Entry.place(y = 1000 * Pos[1])
Entry.place(width = 1000 * Dim[0])
Entry.place(height = 1000 * Dim[1])
Entry.config(justify = Style[0])
Entry.config(state = Style[1])
Entry.config(font = Style[2])
Entry.config(textvariable = Var)
Entry.config(values = Val)
return Entry
# Function to add entry to root
# that allows one or more elements
# from some given list 'Val'
def ListEntry(Root, Pos, Dim, Style, Var, Val):
Entry = tk.Listbox(Root)
Entry.place(x = 1000 * Pos[0])
Entry.place(y = 1000 * Pos[1])
Entry.place(width = 1000 * Dim[0])
Entry.place(height = 1000 * Dim[1])
Entry.config(justify = Style[0])
Entry.config(state = Style[1])
Entry.config(font = Style[2])
Entry.config(selectmode = 'multiple')
Entry.config(listvariable = Var)
Entry.insert(tk.END, *Val)
return Entry
# Function to add entry to root
# that allows one line or more
# without further restrictions
def TextEntry(Root, Pos, Dim, Style, Var):
Entry = tk.Text(Root)
Entry.place(x = 1000 * Pos[0])
Entry.place(y = 1000 * Pos[1])
Entry.place(width = 1000 * Dim[0])
Entry.place(height = 1000 * Dim[1])
#Entry.config(justify = Style[0]) # Non-existent attribute
Entry.config(state = Style[1])
Entry.config(font = Style[2])
#Entry.config(variable = Var) # Non-existent attribute
return Entry
# Create root and add entries
dims = [0.200,0.050]
style = ['l','normal','Calibri 12']
root = CreateRoot([0,0], [500,500], '#DDDDDD', 'Title')
tkvars = [tk.StringVar(), tk.StringVar(), tk.StringVar()]
entry2 = CombEntry(root, [0.025,0.025], dims, style, tkvars[0], ['A','B','C'])
entry3 = ListEntry(root, [0.025,0.100], dims, style, tkvars[1], ['A','B','C'])
entry1 = TextEntry(root, [0.025,0.175], dims, style, tkvars[2])
root.mainloop()
# Print user input without having used
# a tk.button with command
user_input = [i.get() for i in tkvars]
print('user_input = {}'.format(user_input))
print('\nnotice how user_input[0] is correct..')
print('but user_input[1] and user_input[2] are incorrect')