3

我有几个不同的函数要调用,但我想使用变量的值来执行它。我在 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()
4

2 回答 2

1

如果您想使用函数名称作为字符串调用函数,请参阅此问题/答案 - Calling a function of a module from a string with the function's name in Python

几个例子:

首先在全局符号表中查找函数——

def foo(): 
  print 'hello world'

globals()['foo']()
# > hello world

或者第二,如果您的函数是类上的方法 -

class Foo(object): 
  def bar(self): 
    print 'hello world'

foo = Foo()

getattr( foo, 'bar' )()
# > hello world
于 2015-05-30T03:45:42.567 回答
0
def afunc():
    foo.set('A')
    tempchoice.set('afuncaction')
    global myfunc
    myfunc = afuncaction # save a reference to this function

...

if messagebox.askyesno:
    myfunc()

顺便说一句,你不需要在return. 这是一个语句,而不是一个函数。并且没有必要将它放在每个函数的末尾 - 如果一个函数到达其可用语句的末尾,它将return自动(返回 value None)。

于 2015-05-30T04:24:32.703 回答