【问题标题】:How can I return the result of a user selection via a tkinter dialog?如何通过 tkinter 对话框返回用户选择的结果?
【发布时间】:2019-11-22 12:33:41
【问题描述】:

我正在尝试编写一个函数来创建一个 tkinter 对话框,该对话框向用户提供一系列选择选项并要求他们选择一个。我的问题是,当我按下按钮关闭对话框时,我的程序只是挂起并且不会继续下一步。我没有收到帮助我调试的错误消息。

请在此处查看我的代码:

import tkinter as tk

class Option():
    """
    Dumnmy class for user option
    """
    def __init__(self, display_name, item_name):
        self.DisplayName = display_name
        self.ItemName = item_name

def user_selection(options):
    """
    Tkinter popup to make the user choose from a list of options
    Doesn't work - crashes on exit
    """
    tk_root = tk.Tk()
    selection = tk.StringVar()
    selection.set("1") # initial value

    for option in options:
        radio = tk.Radiobutton(tk_root, text=option.DisplayName, value=option.ItemName, var=selection)
        radio.pack()
    button = tk.Button(tk_root, text='OK', command=tk_root.destroy)
    button.pack()

    tk_root.mainloop()
    user_choice = selection.get()
    return user_choice

avaliable_options = [Option('Apple', 'apple_url'), Option('Banana', 'banana_url')]
selection = user_selection(avaliable_options)
print(selection)

我已经在这个上用尽了我的 Google-foo,谁能告诉我做错了什么?

【问题讨论】:

  • selection.get().destroy() 之后无法访问,请先保存。相关tkinter-dialog-windows
  • 您可以在[list of options] 中添加真实数据,以便我们运行它。
  • 如果我将一些数据放入[list of options] 并使用print(selection),那么它对我有用。也许您会在控制台/终端中针对代码的不同部分收到一些错误消息。
  • 如果您运行它时遇到其他问题,那么问题可能是您使用Tk() 创建第二个窗口 - 它应该仅用于创建主窗口。对于其他窗口,请使用Toplevel()。或问题可能是第二个mainloop()。 Tkinter 应该只使用一个 mainloop()
  • 您好,感谢 cmets,他们帮助我排除故障。通过添加一个虚拟 [选项列表],我的代码可以正常工作,这让我感到惊讶。原来我的问题是我使用另一个 Tk() 生成文件对话框并且在使用后没有正确销毁的程序中的早期点。感谢您的帮助。

标签: python python-3.x tkinter


【解决方案1】:

我已经破解了你的代码,问题很简单:你必须把主循环放在程序的末尾,因为当编译器读取这些函数时,它不会编译下一个代码。但是,如果您对根目录使用更新功能,则可以产生类似的效果。 所以修改的代码如下:

import tkinter as tk

class Option():
    """
    Dumnmy class for user option
    """
    def __init__(self, display_name, item_name):
        self.DisplayName = display_name
        self.ItemName = item_name

def user_selection(options):
    """
    Tkinter popup to make the user choose from a list of options
    Doesn't work - crashes on exit
    """
    tk_root = tk.Tk()
    selection = tk.StringVar()
    selection.set("1") # initial value

    for option in options:
        radio = tk.Radiobutton(tk_root, text=option.DisplayName, value=option.ItemName, var=selection)
        radio.pack()
    button = tk.Button(tk_root, text='OK', command=tk_root.destroy)
    button.pack()

    tk_root.update()
    user_choice = selection.get()
    return user_choice

avaliable_options = [Option('Apple', 'apple_url'), Option('Banana', 'banana_url')]
selection = user_selection(avaliable_options)
print(selection)

tk_root.mainloop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    相关资源
    最近更新 更多