2017-08-10 81 views
1

下面是下拉菜單的代碼。我希望根據選擇的內容來執行功能。我將如何做到這一點。是否有一段代碼可以讀取選擇內容,並且如果選定了某個內容,它將執行所需的功能。下拉菜單啓動功能

from tkinter import * 
from tkinter.ttk import * 
import time 

def menu(): 

    root = Tk() 
    root.title("Menu") 

    menu = Frame(root) 
    menu.pack(pady = 5, padx = 50) 
    var = StringVar(root) 

def printgender(): 
    print("q") 

    options = [ 
     'Unique ID number', 
     'Surname', 
     'Forename', 
     'Date of birth', 
     'Home address', 
     'Home phone number', 
     'Gender', 
     'Tutor group', 
     'Email address', 
    ] 
    option = OptionMenu(menu, var, options[0], *options) 

    var.set('Select') 

    option.grid(row = 1, column = 1) 

    root.mainloop() 

回答

1

假設你要選擇從OptionMenu那麼這可以通過爲OptionMenu設置command實現一個option後發生的動作,看到我的代碼示例下面的一個示範開始:

from tkinter import * 

root = Tk() 

def command(*args): 
    print(var.get()) 

var = StringVar() 
var.set("one") 

option = OptionMenu(root, var, "one", "two", "three", command=command) 

option.pack() 

root.mainloop() 

另外,你也可以用一個按鈕做到這一點,如下所示:

from tkinter import * 

root = Tk() 

def command(*args): 
    print(var.get()) 

var = StringVar() 
var.set("one") 

option = OptionMenu(root, var, "one", "two", "three") 
button = Button(root, text="Ok", command=command) 

option.pack() 
button.pack() 

root.mainloop()