在使用Python和Tkinter时,如何根据选项菜单中选择的选项使按钮按下时执行不同的操作?

2024-05-16 12:06:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个简单的GUI,我现在的目标是让用户选择一个选项(运动学或电),然后他们会按下按钮,进入一个新的屏幕。目前,按钮将做同样的事情,无论是选择,我不知道如何改变这一点。我正在使用python3.6.1

from tkinter import *
import tkinter.font

bg_color1 = "#008B8B"

abc = Tk()

abc.title("Physics Problem Solver")
abc.rowconfigure(0, weight=1)
abc.columnconfigure(0, weight=1)

helvetica_bold_16 = tkinter.font.Font(
    root = abc, 
    family="Helvetica",
    weight="bold",
    size=16)

helvetica_bold_12 = tkinter.font.Font(
    root = abc,
    family="Helvetica",
    weight="bold",
    size=12)

app = Frame(abc,
    bd=6,
    relief="groove",
    bg=bg_color1)
app.rowconfigure(0, weight=1)
app.columnconfigure(0, weight=1)
app.grid(sticky=N+S+E+W)

msg1 = Message(app, 
    text = "Welcome to the Physics Problem Solver!",
    font=helvetica_bold_16,
    bg=bg_color1,
    fg="white",
    justify="center",
    relief="flat")
msg1.grid(pady=15)

def callback1():
    toplevel = Toplevel()
    toplevel.title("Window 2")
    toplevel.focus_set()

optionList = ("Kinematics",
    "Electricity")
om1v= StringVar()
om1v.set(optionList[0])

om1 = OptionMenu(app,
    om1v,
    "Kinematics",
    "Electricity")
om1.grid(pady=20)

b1= Button(app, 
    text="Go!",
    width=5,
    activebackground="#007070",
    activeforeground="#00ACAC",
    fg="black", 
    justify="center",
    font=helvetica_bold_12,
    relief="raised",
    command=callback1)
b1.grid(pady=20)

abc.mainloop()

Tags: apptkinter按钮gridbgabcfontweight
1条回答
网友
1楼 · 发布于 2024-05-16 12:06:34

你没什么特别需要做的。在回调中,您可以获取选项菜单的值,然后执行任何适当的操作。你知道吗

def callback1():
    if om1v.get() == "Kinematics":
        do_kinematics
    else:
        do_electricity()

相关问题 更多 >