How can I create a dropdown menu from a List in Tkinter?

后端 未结 1 886
我寻月下人不归
我寻月下人不归 2021-01-31 09:12

I am creating a GUI that builds information about a person. I want the user to select their birth month using a drop down bar, with the months configured earlier as a list forma

1条回答
  •  生来不讨喜
    2021-01-31 10:16

    To create a "drop down menu" you can use OptionMenu in tkinter

    Example of a basic OptionMenu:

    from Tkinter import *
    
    master = Tk()
    
    variable = StringVar(master)
    variable.set("one") # default value
    
    w = OptionMenu(master, variable, "one", "two", "three")
    w.pack()
    
    mainloop()
    

    More information (including the script above) can be found here.


    Creating an OptionMenu of the months from a list would be as simple as:

    from tkinter import *
    
    OPTIONS = [
    "Jan",
    "Feb",
    "Mar"
    ] #etc
    
    master = Tk()
    
    variable = StringVar(master)
    variable.set(OPTIONS[0]) # default value
    
    w = OptionMenu(master, variable, *OPTIONS)
    w.pack()
    
    mainloop()
    

    In order to retrieve the value the user has selected you can simply use a .get() on the variable that we assigned to the widget, in the below case this is variable:

    from tkinter import *
    
    OPTIONS = [
    "Jan",
    "Feb",
    "Mar"
    ] #etc
    
    master = Tk()
    
    variable = StringVar(master)
    variable.set(OPTIONS[0]) # default value
    
    w = OptionMenu(master, variable, *OPTIONS)
    w.pack()
    
    def ok():
        print ("value is:" + variable.get())
    
    button = Button(master, text="OK", command=ok)
    button.pack()
    
    mainloop()
    

    I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.

    0 讨论(0)
提交回复
热议问题