为什么在声明时执行Button参数“command”?

为什么在声明时执行Button参数“command”?

我的代码是:


from Tkinter import *


admin = Tk()

def button(an):

    print an

    print 'het'


b = Button(admin, text='as', command=button('hey'))

b.pack()

mainloop()

按钮不起作用,它在没有我的命令的情况下打印'hey'和'het',然后,当我按下按钮时没有任何反应。


BIG阳
浏览 1353回答 4
4回答

呼唤远方

您需要创建一个没有参数的函数,您可以将其用作命令:b = Button(admin, text='as', command=lambda: button('hey'))请参阅本文档的“将参数传递给回调”部分。

慕的地8271018

当引擎在“... command = ...”行分配值时,引擎会评估函数的结果。“命令”期望返回一个函数,这就是为什么使用lambda可以完成这项工作,因为它创建了一个在评估期间返回“命令”的异常函数。您也可以编写自己的功能,它也可以完成这项工作。这是一个lambda和没有lambda的例子:#!/usr/bin/python# coding=utf-8from Tkinter import *# Creation de la fenêtre principale (main window)Mafenetre = Tk()res1 = StringVar()res2 = StringVar()def isValidInput(obj):    if hasattr(obj, 'get') and callable(getattr(obj, 'get')):        return TRUE    return FALSE# stupid action 2 (return 12 on purpose to show potential mistake)def action1(*arguments):    print "action1 running"    for arg in arguments:        if isValidInput(arg):            print "input value: ", arg.get()            res1.set(arg.get())        else:            print "other value:", arg    print "\n"    return 12# stupid action 2def action2(*arguments):    print "action2 running"    a = arguments[0]    b = arguments[1]    if isValidInput(a) and isValidInput(b):        c = a.get() + b.get()        res2.set(c)        print c    print "\n"# a stupid workflow manager ordered by namedef start_tasks(*arguments, **keywords):    keys = sorted(keywords.keys())    for kw in keys:        print kw, "plugged "        keywords[kw](*arguments)# valid callback wrapper with lambdadef action1_callback(my_input):    return lambda args=[my_input]: action1(*args)# valid callback wrapper without lambdadef action1_callback_nolambda(*args, **kw):    def anon():        action1(*args)    return anon# first input stringinput1 = StringVar()input1.set("delete me...")f1 = Entry(Mafenetre, textvariable=input1, bg='bisque', fg='maroon')f1.focus_set()f1.pack(fill="both", expand="yes", padx="5", pady=5)# failed callback because the action1 function is evaluated, it will return 12. # in this case the button won't work at all, because the assignement expect a function # in order to have the button command to execute somethingba1 = Button(Mafenetre)ba1['text'] = "show input 1 (ko)"ba1['command'] = action1(input1)ba1.pack(fill="both", expand="yes", padx="5", pady=5)# working button using a wrapperba3 = Button(Mafenetre)ba3['text'] = "show input 1 (ok)"# without a lambda it is also working if the assignment is a function#ba1['command'] = action1_callback_nolambda(input1)ba3['command'] = action1_callback(input1)ba3.pack(fill="both", expand="yes", padx="5", pady=5)# display result labelLabel1 = Label(Mafenetre, text="Action 1 result:")Label1.pack(fill="both", expand="yes", padx="5", pady=5)# display result valueresl1 = Label(Mafenetre, textvariable=res1)resl1.pack(fill="both", expand="yes", padx="5", pady=5)# second input stringinput2 = StringVar()f2 = Entry(Mafenetre, textvariable=input2, bg='bisque', fg='maroon')f2.focus_set()f2.pack(fill="both", expand="yes", padx="5", pady=5)# third test without wrapper, but making sure that several arguments are well handled by a lambda functionba2 = Button(Mafenetre)ba2['text'] = "execute action 2"ba2['command'] = lambda args=[input1, input2], action=action2: start_tasks(*args, do=action)ba2.pack(fill="both", expand="yes", padx="5", pady=5)# display result labelLabel2 = Label(Mafenetre, text="Action 2 result:")Label2.pack(fill="both", expand="yes", padx="5", pady=5)# display result valueresl2 = Label(Mafenetre, textvariable=res2)resl2.pack(fill="both", expand="yes", padx="5", pady=5)Mafenetre.mainloop()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python