commands in Tkinter

后端 未结 3 801
死守一世寂寞
死守一世寂寞 2021-01-15 11:07

I have the following code by it isn\'t working any ideas?

相关标签:
3条回答
  • 2021-01-15 11:40

    A few issues here. and is a logical and, so you can't use it like that.

    Second, you are calling your second function with the parentheses instead of passing the function itself. This means that you are passing the return value of a function as the command. So if we had a function

    def my_func():
        return 'hello'
    

    passing in command = my_func will make the button call my_func(). If you try to pass in command = my_func(), you end up passing in the string hello which doesn't make sense.

    Third, a solution would be to wrap both functions in a separate function. To do this inline, you can use a lambda function that calls both functions (in this case, you would want the parentheses). Or you can just define this function separately and call both of the functions you want.

    Here are the examples:

    def on_button_submit():
        main_menu()
        appending_to_text_file()
    

    So then you an use this on_button_submit as the command for your button.

    Or use a lambda function. Here is a quick example of how lambda function would work:

    def func1():
      print('in func1')
    
    def func2():
      print('in func2')
    
    x = lambda : (func1(), func2())
    x()
    

    So you can use the following as your button command:

    lambda : (main_menu(), appending_to_text_file())
    
    0 讨论(0)
  • 2021-01-15 11:45

    This parameter will not accept two functions. The best way for you to solve this is to create a function that performs all other functions.

    def main_menu():
        pass
    
    
    def apending_to_text_file():
        pass
    
    
    def commands():
        main_menu()
        apending_to_text_file()
    
    
    login_button = Button(
        root, text="Click here to enter data",
        command=commands
    )
    
    0 讨论(0)
  • 2021-01-15 11:49

    You can try something like this using lambda function

    login_button = Button(root, text="Click here to enter data", command=lambda:[main_menu(),apending_to_text_file()])
    
    0 讨论(0)
提交回复
热议问题