微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在不使用 tk.Button 的情况下从 tk.Text 和 tk.Listbox 获取用户输入

如何解决在不使用 tk.Button 的情况下从 tk.Text 和 tk.Listbox 获取用户输入

我使用 npm install --save-dev tsconfig-paths 库在 Python 中制作了一个 UI。不幸的是,我不知道如何在不使用按钮的情况下从 tkintertk.Text 小部件获取用户输入。我试图将用户输入分配给一个变量,该变量在使用按钮调用 tk.ListBox 或手动关闭 UI 时立即采用永久值。这适用于 root.destroytk.Entry 等小部件。我想知道如何让它也适用于 tk.Radiobuttontk.Text 小部件。下面显示一个示例代码,希望它能阐明我正在尝试做的事情。

tk.ListBox

解决方法

如果您只想在小部件中输入最后一个值,您可以使用根窗口的协议处理程序。

# Import tkinter library
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.messagebox import askyesno

...

entry1 = TextEntry(root,[0.025,0.175],dims,style,tkvars[2])

# works when GUI is closed manually,close button [x],Alt + F4
# protocol handler
def close():
    # creating global variables in a function
    global combobox_value,listbox_value,text_value
    combobox_value = entry2.get()
    # entry3.curselection() is a tuple with the indices of the selected list items
    listbox_value = [entry3.get(i) for i in entry3.curselection()]
    text_value = entry1.get("1.0","end-1c")
    # optional,validation of values
    if not all([combobox_value,text_value]):
        answer = askyesno(title="Info",message="Not all values have been selected. " \
                                                "Close the application anyway?")
        if not answer: # False
            return
    root.destroy()
    
# exit with saving data
root.protocol("WM_DELETE_WINDOW",close)

root.mainloop()

# Print user input without having used
# a tk.button with command
print("User input:",combobox_value,text_value)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。