Have multiple commands when button is pressed

自作多情 提交于 2019-12-28 12:34:06

问题


I want to run multiple functions when I click a button. For example I want my button to look like

self.testButton = Button(self, text = "test", 
                         command = func1(), command = func2())

when I execute this statement I get an error because I cannot allocate something to an argument twice. How can I make command execute multiple functions.


回答1:


You could create a generic function for combining functions, it might look something like this:

def combine_funcs(*funcs):
    def combined_func(*args, **kwargs):
        for f in funcs:
            f(*args, **kwargs)
    return combined_func

Then you could create your button like this:

self.testButton = Button(self, text = "test", 
                         command = combine_funcs(func1, func2))



回答2:


You can simply use lambda like this:

self.testButton = Button(self, text=" test", command=lambda:[funct1(),funct2()])



回答3:


def func1(evt=None):
    do_something1()
    do_something2()
    ...

self.testButton = Button(self, text = "test", 
                         command = func1)

maybe?

I guess maybe you could do something like

self.testButton = Button(self, text = "test", 
                         command = lambda x:func1() & func2())

but that is really gross ...




回答4:


You can use the lambda for this:

self.testButton = Button(self, text = "test", lambda: [f() for f in [func1, funct2]])



回答5:


Button(self, text="text", command=func_1()and func_2)




回答6:


I've found also this, which works for me. In a situation like...

b1 = Button(master, text='FirstC', command=firstCommand)
b1.pack(side=LEFT, padx=5, pady=15)

b2 = Button(master, text='SecondC', command=secondCommand)
b2.pack(side=LEFT, padx=5, pady=10)

master.mainloop()

... you can do...

b1 = Button(master, command=firstCommand)
b1 = Button(master, text='SecondC', command=secondCommand)
b1.pack(side=LEFT, padx=5, pady=15)

master.mainloop()

What I did was just renaming the second variable b2 the same as the first b1 and deleting, in the solution, the first button text (so only the second is visible and will act as a single one).

I also tried the function solution but for an obscure reason it don't work for me.




回答7:


this is a short example : while pressing the next button it will execute 2 functions in 1 command option

    from tkinter import *
    window=Tk()
    v=StringVar()
    def create_window():
           next_window=Tk()
           next_window.mainloop()

    def To_the_nextwindow():
        v.set("next window")
        create_window()
   label=Label(window,textvariable=v)
   NextButton=Button(window,text="Next",command=To_the_nextwindow)

   label.pack()
   NextButton.pack()
   window.mainloop()


来源:https://stackoverflow.com/questions/13865009/have-multiple-commands-when-button-is-pressed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!