gpt4 book ai didi

python - 阻止输入对话框

转载 作者:行者123 更新时间:2023-12-01 04:21:48 25 4
gpt4 key购买 nike

如何在标准 Python 中获得阻塞模式输入对话框?

我需要用户输入一个值,然后代码才能继续。

这里有一些无法工作的测试代码,但我的想法是我应该能够从脚本中的任何位置调用MyDialog,所以这只是一个简化的示例。

import tkinter

class MyDialog:
def __init__(self, prompt):
self.top = tkinter.Toplevel()
tkinter.Label(self.top, text=prompt).pack()
self.e = tkinter.Entry(self.top)
self.e.pack(padx=5)
tkinter.Button(self.top, text="OK", command=self.ok).pack(pady=5)

def ok(self):
self.top.destroy()
return self.e.get()


root = tkinter.Tk()
userName = MyDialog('Enter your name')
tkinter.Label(root, text="Hello {}".format(userName)).pack()

root.mainloop()

该对话框不仅应该禁用主窗口,还应该阻止调用它的任何代码。并且它应该能够将值传递回调用代码。

最佳答案

该解决方案需要两个关键部分。首先,使用grab_set阻止另一个窗口中的所有事件(或者更正确地说,将所有事件发送到对话窗口)。其次,使用 wait_window 来防止该方法在对话框被销毁之前返回。

话虽如此,您不应该像示例中那样使用它。在创建窗口之前,您需要运行mainloop。它可能在某些平台上工作正常,但一般来说,在 mainloop 运行之前,您不应期望 GUI 能够正常运行。

这是一个简单的例子:

import Tkinter as tk

class MyDialog(object):
def __init__(self, parent, prompt):
self.toplevel = tk.Toplevel(parent)
self.var = tk.StringVar()
label = tk.Label(self.toplevel, text=prompt)
entry = tk.Entry(self.toplevel, width=40, textvariable=self.var)
button = tk.Button(self.toplevel, text="OK", command=self.toplevel.destroy)

label.pack(side="top", fill="x")
entry.pack(side="top", fill="x")
button.pack(side="bottom", anchor="e", padx=4, pady=4)

def show(self):
self.toplevel.grab_set()
self.toplevel.wait_window()
value = self.var.get()
return value

class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)

self.button = tk.Button(self, text="Click me!", command=self.on_click)
self.label = tk.Label(self, text="", width=40)
self.label.pack(side="top", fill="x")
self.button.pack(padx=20, pady=20)

def on_click(self):
result = MyDialog(self, "Enter your name:").show()
self.label.configure(text="your result: '%s'" % result)

if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()

关于python - 阻止输入对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33595791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com