Python 创建Tkinter类并等待返回值
我有一门tkinter课程:Python 创建Tkinter类并等待返回值,python,user-interface,tkinter,Python,User Interface,Tkinter,我有一门tkinter课程: class DBCreatorWin(): def closeWindow(self): tkMessageBox.showinfo("Ilmiont SQLite Database Manager", "This window cannot be closed.\nEnter a database name and press Continue.") def returnName(self): dbName = s
class DBCreatorWin():
def closeWindow(self):
tkMessageBox.showinfo("Ilmiont SQLite Database Manager", "This window cannot be closed.\nEnter a database name and press Continue.")
def returnName(self):
dbName = self.entry.get()
self.window.destroy()
return dbName
def __init__(self):
self.window = Toplevel()
self.window.transient(tkRoot)
self.window.grab_set()
self.window.resizable(width=False, height=False)
self.window.title("Ilmiont SQLite Database Manager")
self.window.protocol("WM_DELETE_WINDOW", self.closeWindow)
self.label = Label(self.window, text="Enter the name of the database to be created: ")
self.entry = Entry(self.window, width=30)
self.button = Button(self.window, text="Continue", command=self.returnName)
self.label.grid(row=0, column=0)
self.entry.grid(row=0, column=1)
self.button.grid(row=1, column=0, columnspan=2)
我想在我的主代码中创建这个类的一个实例,并等待返回值。用户在输入字段中键入一个名称,然后按下“继续”按钮。此时,该值应返回到类最初实例化的位置。我该怎么办?我似乎不能让它正常工作,我是新来的
提前感谢,,
你不能这样做
tkinter的整个工作方式都是回调。您正在使用的命令是回调,您必须在类中使用该值。以下是一个例子:
def do_stuf(self):
tkMessageBox.showinfo("Foo", returnName())
....................
self.button = Button(self.window, text="Continue", command=self.do_stuff)
有几种方法可以做到这一点。基本思想是使用tkinter方法在返回之前等待特定事件。Tkinter提供了两种方法来实现这一点:和。最常见的方法是打开一个窗口,然后等待它被销毁。一些好的例子可以在effbot网站上找到,标题为 这里有一个简单的例子。它还没有准备好生产,但说明了总体思路。至少你会想在对话框上添加一个抓取,这样你就不能在对话框打开时与主窗口交互,因为你说过你希望对话框是模态的
import Tkinter as tk
class MyDialog(object):
def __init__(self, parent):
self.toplevel = tk.Toplevel(parent)
self.var = tk.StringVar()
label = tk.Label(self.toplevel, text="Pick something:")
om = tk.OptionMenu(self.toplevel, self.var, "one", "two","three")
button = tk.Button(self.toplevel, text="OK", command=self.toplevel.destroy)
label.pack(side="top", fill="x")
om.pack(side="top", fill="x")
button.pack()
def show(self):
self.toplevel.deiconify()
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, width=80)
self.label.pack(side="top", fill="x")
self.button.pack(pady=20)
def on_click(self):
result = MyDialog(self).show()
self.label.configure(text="your result: %s" % result)
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()
调用
mainloop
后,正常的代码流将不会继续,直到窗口关闭。如果希望GUI保持打开状态,则必须从GUI中调用代码逻辑。如果没有事件驱动,很难说您当前做错了什么。听起来您可能希望使用类似于非事件驱动的模块的东西。感谢您提供此解决方案。它工作得很好。在一些额外的搜索之后,我遇到了tkSimpleDialog.askstring,它实际上很好地解决了我的问题。