[英]closing tkinter menu after selection is made
I Found this script on pythonspot tutorial, But I can't make it close after a selection has been made, I tried adding root.destroy()
but it didn't do it.我在pythonspot教程上找到了这个脚本,但是在做出选择后我无法关闭它,我尝试添加
root.destroy()
但它没有这样做。 What I want is basically to store the selection in a variable (so I can use later on) and destroy the window after selection.我想要的基本上是将选择存储在一个变量中(以便我以后可以使用)并在选择后销毁 window。 I am very new to
tkinter
我对
tkinter
很陌生
from tkinter import *
root = Tk()
root.title("Tk dropdown example")
# Add a grid
mainframe = Frame(root)
mainframe.grid(column=0,row=0, sticky=(N,W,E,S) )
mainframe.columnconfigure(0, weight = 1)
mainframe.rowconfigure(0, weight = 1)
mainframe.pack(pady = 100, padx = 100)
# Create a Tkinter variable
tkvar = StringVar(root)
# Dictionary with options
choices = { 'Pizza','Lasagne','Fries','Fish','Potatoe'}
tkvar.set('Pizza') # set the default option
popupMenu = OptionMenu(mainframe, tkvar, *choices)
Label(mainframe, text="Choose a dish").grid(row = 1, column = 1)
popupMenu.grid(row = 2, column =1)
# on change dropdown value
def change_dropdown(*args):
print( tkvar.get() )
# link function to change dropdown
tkvar.trace('w', change_dropdown)
root.mainloop()
#root.destroy()
You can use the command
option of the OptionMenu
to execute a function when the user selects an item (taking the chosen item in argument).当用户选择一个项目时,您可以使用
OptionMenu
的command
选项执行 function(在参数中获取所选项目)。 In this function, you will close the window and assign the user choice to a global variable so that you can reuse it after closing GUI:在此 function 中,您将关闭 window 并将用户选择分配给全局变量,以便您可以在关闭 GUI 后重用它:
def on_selection(value):
global choice
choice = value
root.destroy()
Here is a full example:这是一个完整的例子:
import tkinter as tk
root = tk.Tk()
# Create a Tkinter variable
tkvar = tk.StringVar(root)
# options
choices = ['Pizza','Lasagne','Fries','Fish','Potatoe']
tkvar.set('Pizza') # set the default option
def on_selection(value):
global choice
choice = value # store the user's choice
root.destroy() # close window
popupMenu = tk.OptionMenu(root, tkvar, *choices, command=on_selection)
tk.Label(root, text="Choose a dish").grid(row=0, column=0)
popupMenu.grid(row=1, column =0)
root.mainloop()
# Do whatever you want with the user's choice after closing the window
print('You have chosen %s' % choice)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.