【问题标题】:Calling functions in tkinter在 tkinter 中调用函数
【发布时间】:2016-04-29 16:06:08
【问题描述】:

对于线路:

 file_Menu.add_command(label = 'New', command = do_Nothing)

为什么函数叫command = do_Nothing而不是command = do_Nothing()

整个代码如下:

# Tkinter GUI Menu

from tkinter import *

### Functions ###

# Do Nothing
def do_Nothing():
    print('I just did... nothing')



### Create tkinter window ###

# Create Window
root = Tk() 



#### Creating the Menu(s) ###

# Create the Menu Bar
menu_Bar = Menu(master = root)

# Create File Menu
file_Menu = Menu(master = menu_Bar)



### Displaying the Menu(s) ###

# Display Menu Bar
root.config(menu = menu_Bar)

# Display File Menu
menu_Bar.add_cascade(label = 'File', menu = file_Menu)




### File Menu Properties ####

# New
file_Menu.add_command(label = 'New', command = do_Nothing)

# Open
file_Menu.add_command(label = 'Open', command = do_Nothing)

# Exit
file_Menu.add_command(label = 'Exit', command = root.quit) 




### Display tkinter window ###
root.mainloop()

【问题讨论】:

    标签: function user-interface python-3.x menu tkinter


    【解决方案1】:

    Tkinter 是普通的 python,所以它遵循普通的 python 规则:如果你使用一个函数名后跟括号,python 将立即执行该函数并返回结果。

    所以,当你这样做时:

    file_Menu.add_command(..., command = do_Nothing())
    

    ...这和你这样做完全一样:

    nothing = do_Nothing()
    file_Menu.add_command(..., command = nothing)
    

    当您在绑定或command 回调中指定命令时,您必须告诉 tkinter 该命令的名称(或更准确地说,该命令的引用 )。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-12
      • 2015-12-08
      • 2018-07-03
      • 1970-01-01
      • 1970-01-01
      • 2021-05-26
      相关资源
      最近更新 更多