使用 Tkinter 下拉菜单选项作为不同命令的标准

Using Tkinter Drop-Down Menu choices as criteria for different commands

我被指派创建一个我选择的简单 Python 项目,目前我正在开发一个小的 Tkinter GUI 应用程序。成功编写了负责多个下拉菜单的代码部分后,我想知道如何使用用户选择的选项组合来创建打开指定 window 的命令。有什么巧妙的方法吗?在构造按钮命令的函数中以某种方式定义选项组合就足够了吗?非常感谢您对此的任何建议。

#first drop-down menu
 options1 = [
    '............',
    '............',
    '............'
]
chosen1 = StringVar()
chosen1.set('............')

vyber1 = OptionMenu(whiteboard, chosen1, *options1)
vyber1.place(relx = 0.35, rely = 0.35, relwidth = 0.35, relheight = 0.05)

# second drop-down menu
options2 = [
    '............',
    '............',
    '............',
    '............'
]
chosen2 = StringVar()
chosen2.set('............')

vyber2 = OptionMenu(whiteboard, chosen2, *options2)
vyber2.place(relx = 0.35, rely = 0.46, relwidth = 0.35, relheight = 0.05)

#third drop-down menu
options3 = [
    '............',
    '............',
    '............',
    '............'
]
chosen3 = StringVar()
chosen3.set('............')

vyber3 = OptionMenu(whiteboard, chosen3, *options3)
vyber3.place(relx = 0.35, rely = 0.57, relwidth = 0.35, relheight = 0.05)

在 Python 中“整洁”和有序的方法是 map 将每个选择组合映射到所需的 window-opening 函数字典。查找要调用的函数只是将当前选择组合在一起形成一个字典键,然后使用它来 look-up 相应的函数来调用。

下面是一个可运行的例子:

import tkinter as tk
from tkinter import messagebox


whiteboard = tk.Tk()
whiteboard.geometry('300x300')

#first drop-down menu
options1 = ['1', '2', '3']
chosen1 = tk.StringVar(value=options1[0])

vyber1 = tk.OptionMenu(whiteboard, chosen1, *options1)
vyber1.place(relx=0.35, rely=0.35, relwidth=0.35, relheight=0.10)

# second drop-down menu
options2 = ['A', 'B', 'C', 'D']
chosen2 = tk.StringVar(value=options2[0])

vyber2 = tk.OptionMenu(whiteboard, chosen2, *options2)
vyber2.place(relx=0.35, rely=0.46, relwidth=0.35, relheight=0.10)

#third drop-down menu
options3 = ['Red', 'Green', 'Blue', 'Yellow']
chosen3 = tk.StringVar(value=options3[0])

vyber3 = tk.OptionMenu(whiteboard, chosen3, *options3)
vyber3.place(relx=0.35, rely=0.57, relwidth=0.35, relheight=0.10)

# Window opening functions.
def open_window_1ARed():
    new_win = tk.Toplevel(whiteboard)
    new_win.geometry('300x100')
    new_win.title('1-A-Red window')
    tk.Label(new_win, text='Hello world').pack()

def open_window_1BBlue():
    new_win = tk.Toplevel(whiteboard)
    new_win.geometry('300x100')
    new_win.title('1-B-Blue window')
    tk.Label(new_win, text='Hello world').pack()

def display_error():
    messagebox.showerror('Sorry', "Unsupported combination!")

# Dictionary mapping combinations of choices to functions.
open_windows_commands = {
    '1ARed': open_window_1ARed,
    '1BBlue': open_window_1BBlue,
}

def open_window():
    key = f'{chosen1.get()}{chosen2.get()}{chosen3.get()}'  # Create key from choices.
    open_window_command = open_windows_commands.get(key, display_error)
    open_window_command()

btn = tk.Button(whiteboard, text='Open window', command=open_window)
btn.place(relx=0.35, rely=0.80)

whiteboard.mainloop()