commands in Tkinter

后端 未结 3 803
死守一世寂寞
死守一世寂寞 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())
    

提交回复
热议问题