将Python与Tkinter结合使用,如何根据选项菜单中选择的选项,使按钮按下做不同的事情? [英] Using Python with Tkinter, how can I make a button press do a different thing depending on which option is selected in the option menu?
本文介绍了将Python与Tkinter结合使用,如何根据选项菜单中选择的选项,使按钮按下做不同的事情?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在制作一个简单的GUI,现在我的目标是让用户选择一个选项(运动学或电学),然后他们将按下按钮以转到他们选择的一个新屏幕.当前,无论选择哪个按钮,该按钮都将执行相同的操作,并且我不知道如何更改它.我正在使用Python 3.6.1
I'm making a simple GUI, and my goal right now is for the user to select an option (kinematics or electricity) and then they would press the button to move on to a new screen for the one they selected. Currently, the button will do the same thing no matter which is selected, and I don't know how to change that. I'm using Python 3.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()
推荐答案
您不需要做任何特别的事情.在回调中,您可以获取选项菜单的值,然后执行适当的操作.
There's nothing special you need to do. In your callback you can get the value of the option menu and then do whatever is appropriate.
def callback1():
if om1v.get() == "Kinematics":
do_kinematics
else:
do_electricity()
这篇关于将Python与Tkinter结合使用,如何根据选项菜单中选择的选项,使按钮按下做不同的事情?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文