为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

BIG阳 2019-05-22 14:01:41
为什么在声明时执行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',然后,当我按下按钮时没有任何反应。
查看完整描述

4 回答

?
呼唤远方

TA贡献1856条经验 获得超11个赞

您需要创建一个没有参数的函数,您可以将其用作命令:

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

请参阅本文档的“将参数传递给回调”部分。


查看完整回答
反对 回复 2019-05-22
?
慕的地8271018

TA贡献1796条经验 获得超4个赞

当引擎在“... command = ...”行分配值时,引擎会评估函数的结果。


“命令”期望返回一个函数,这就是为什么使用lambda可以完成这项工作,因为它创建了一个在评估期间返回“命令”的异常函数。您也可以编写自己的功能,它也可以完成这项工作。


这是一个lambda和没有lambda的例子:


#!/usr/bin/python

# coding=utf-8


from 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 2

def 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 name

def start_tasks(*arguments, **keywords):

    keys = sorted(keywords.keys())

    for kw in keys:

        print kw, "plugged "

        keywords[kw](*arguments)



# valid callback wrapper with lambda

def action1_callback(my_input):

    return lambda args=[my_input]: action1(*args)



# valid callback wrapper without lambda

def action1_callback_nolambda(*args, **kw):

    def anon():

        action1(*args)

    return anon



# first input string

input1 = 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 something

ba1 = 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 wrapper

ba3 = 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 label

Label1 = Label(Mafenetre, text="Action 1 result:")

Label1.pack(fill="both", expand="yes", padx="5", pady=5)

# display result value

resl1 = Label(Mafenetre, textvariable=res1)

resl1.pack(fill="both", expand="yes", padx="5", pady=5)



# second input string

input2 = 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 function

ba2 = 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 label

Label2 = Label(Mafenetre, text="Action 2 result:")

Label2.pack(fill="both", expand="yes", padx="5", pady=5)

# display result value

resl2 = Label(Mafenetre, textvariable=res2)

resl2.pack(fill="both", expand="yes", padx="5", pady=5)


Mafenetre.mainloop()


查看完整回答
反对 回复 2019-05-22
  • 4 回答
  • 0 关注
  • 1352 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信