对问题的基本性质表示歉意。 Tkinter 让我完全难住了。
我正在尝试构建一个带有菜单栏的应用程序,其中一个选项将弹出一个对话框,用户在其中输入两个值,然后按“Enter”或“Cancel”按钮。按任一按钮都会关闭窗口。
我可以构建主窗口和“弹出窗口”来输入值,我已经完成了在按下按钮后提取文本和关闭窗口的所有示例,但我仍然是空的。这是我想使用的框架:
from Tkinter import *
#
# Functions to perform functions selected from main window
#
def enter_values():
new_window = Toplevel(root)
Label(new_window, text="Value 1").grid(sticky=W,row=0)
e1=Entry(new_window,width=40).grid(row=0,column=1,sticky=W)
Label(new_window, text="Value 2").grid(pady=20,sticky=W,row=1)
e2=Entry(new_window,width=20).grid(row=1,column=1,pady=20,sticky=W)
ok= Button(new_window, text="Enter",command=lambda: callback("OK")).grid(column=0,row=4,pady=30)
cancel = Button(new_window,text="Cancel",command=lambda: callback("CANCEL")).grid(column=1,row=4,pady=30)
def callback(button):
if button == "OK":
print "OK"
elif button == "CANCEL":
print "Cancel"
else:
print "no idea"
#
# Following section defines the display window
#
root = Tk()
root.minsize(500,200)
root.geometry("800x300")
root.wm_title("Some clever title here")
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=enter_values)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
root.mainloop()
最佳答案
您必须通过 new_window.destroy() 关闭窗口。 要从条目中获取文本,请定义变量,将它们分配给条目并在需要时获取值。 不是最好的例子,但类似这样的东西会起作用:
from tkinter import *
#
# Functions to perform functions selected from main window
#
def enter_values():
v1 = StringVar()
v2 = StringVar()
new_window = Toplevel(root)
Label(new_window, text="Value 1").grid(sticky=W,row=0)
Entry(new_window,textvariable=v1,width=40).grid(row=0,column=1,sticky=W)
Label(new_window, text="Value 2").grid(pady=20,sticky=W,row=1)
Entry(new_window,textvariable=v2,width=20).grid(row=1,column=1,pady=20,sticky=W)
ok= Button(new_window, text="Enter",command=lambda: callback("OK",new_window,v1,v2)).grid (column=0,row=4,pady=30)
cancel = Button(new_window,text="Cancel",command=lambda: callback("CANCEL",new_window)).grid(column=1,row=4,pady=30)
def callback(button,new_window,v1=None,v2=None):
if button == "OK":
print("OK")
print(v1.get())
print(v2.get())
elif button == "CANCEL":
print("Cancel")
else:
print("no idea")
new_window.destroy()
#
# Following section defines the display window
#
root = Tk()
root.minsize(500,200)
root.geometry("800x300")
root.wm_title("Some clever title here")
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=enter_values)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
root.mainloop()
关于Python/Tkinter 从输入框中获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19960087/