【发布时间】:2015-08-13 01:10:05
【问题描述】:
我想调用几个不同的函数,但我想使用一个变量的值来执行它。我在 tkinter 中使用按钮来更改变量的值,以及一个选择随机变量的按钮和一个显示当前值的标签(我在下面的代码中省略了这个)。我有另一个按钮,它创建一个 AskYesNo 消息框,以从用户那里确认选择的按钮/变量值是否正确。如果用户选择否,则返回到根窗口。如果用户选择是,我希望程序调用与变量关联的函数。
我是 Python 和 tkinter 的初学者,所以请不要假设我对简单的编码一无所知。谢谢。
下面是一些示例代码:
import random
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
root = Tk()
global tempchoice
global foo
tempchoice = StringVar()
item = StringVar()
def afunc():
foo.set('A')
tempchoice.set('afuncaction')
return()
def afuncaction():
print("Function A called")
return
def bfunc():
foo.set('B')
tempchoice.set('bfuncaction')
return()
def bfuncaction():
print("Function B called")
return
def mystery():
item = ['afuncaction', 'bfuncaction']
result = random.choice(item)
foo.set("Mystery")
tempchoice.set(result)
return()
def confirm():
n = messagebox.askyesno("Selected Choice", "Call " + foo.get() + "?")
if n:
tempchoice
return
aButton = Button(root, text="A Function",command=afunc)
aButton.grid(row=0, column=0, sticky=W+E+N+S)
bButton = Button(root, text="B Function",command=bfunc)
bButton.grid(row=1, column=0, sticky=W+E+N+S)
quitButton = Button(root, text="Quit", command=exit)
quitButton.grid(row=7, column=0, sticky=W+E+N+S)
confirmButton = Button(root, text="Confirm", command=confirm)
confirmButton.grid(row=7, column=7)
root.mainloop()
【问题讨论】:
-
“与变量关联的函数”是指负责变量当前值的函数,例如
afunc()如果是'A'? -
如果用户点击 A 按钮,则调用 afunc,将 tempchoice 设置为 afuncaction。 afuncaction 仅在按下 Confirm 按钮然后用户选择 Yes 时才会调用。
标签: python function variables tkinter tkmessagebox