tkinter中Optionmenu控件是用来设置选择框的,以程序为例:
from tkinter import *
from tkinter import messagebox
class Application(Frame):
def __init__(self,master=None):
super().__init__(master)
self.master = master
self.pack()
self.createwidget()
def createwidget(self):
option = ["西瓜", "香蕉", "菠萝"] # 所有的选项列表
variable = StringVar()
variable.set(option[0]) # 默认选项
op = OptionMenu(self, variable, *option)
op["width"] = 10 # 选项框的长度
op.pack(padx=10, pady=10) # 选项框的位置
# 设置按钮,按下后弹出窗口,提示选的水果名称,即获取变量内容
Button(self, text="确定",command=lambda : self.print_fruit(variable)).pack(pady=20)
def print_fruit(self,variable):
messagebox.showinfo("水果", "您选的水果是:{}".format(variable.get()))
if __name__ == '__main__':
root = Tk()
root.title("optionmenu测试")
root.geometry("300x200")
app = Application(root)
root.mainloop()
如果不明白为什么command=lambda : self.print_fruit(variable)请看我上一篇博客。
程序运行结果
下拉选项并选择“菠萝”,点击确定: