如何防止tkinter程序启动时运行与按钮相关的代码?

时间:2019-08-09 16:19:04

标签: python tkinter

对tkinter或OOP经验很少的Python初学者。

tkinter youtube教程中的功能代码,该代码全局调用了所有tkinter函数,然后将其复制并修改为单独的函数。 现在,代码在启动后立即调用函数。 如果注释了退出按钮,则不再显示照片。 我想念什么?


#simple glossary example demonstrating tkinter basics

#program broken by adding main and attempting to partition into seperate functions

from tkinter import *

dictionary_db = {
    'algorithm' : 'Algorithm: Step by step instructions to complete a task.',
    'bug' : 'Bug: Piece of code that causes a program to fail.'
}

photo_file_name = "logo.png"



#click function used by submit button
def click(text_entry, output):
    entered_text = text_entry.get()
    output.delete(0.0, END)
    try:
        definition = dictionary_db[entered_text]
    except:
        definition = "Sorry not an exisiting word. Please try again."
    output.insert(END, definition)

#exit function used by exit button
def close_window(window):
    window.destroy()
    exit()

#configure window
def config(window):

    # config
    window.title("My tkinter demo")
    window.configure(background="black")

    #create objects
    photo1 = PhotoImage(file=photo_file_name)
    photo_label = Label (window, image=photo1, bg="black")
    entry_label = Label(window, text="Enter the word you would like a definition for: ", bg="black", fg="white", font="none 12 bold")
    text_entry = Entry(window, width=20, bg="white")
    output = Text(window, width=75, height=6, wrap=WORD, background="white")
    submit_button = Button(window, text="SUBMIT", width=6, command=click(text_entry, output)) 
    definition_label = Label (window, text="\nDefinition", bg="black", fg="white", font="none 12 bold")
    exit_label = Label (window, text="click to exit", bg="black", fg="white", font="none 12 bold")
    exit_button = Button(window, text="Exit", width=6, command=close_window(window))

    #place objects
    photo_label.grid(row=0, column=0, sticky=E)
    entry_label.grid(row=1, column=0, sticky=W)
    text_entry.grid(row=2, column=0, sticky=W)
    submit_button.grid(row=3, column=0, sticky=W)
    definition_label.grid(row=4, column=0, sticky=W)
    output.grid(row=5, column=0, columnspan=2, sticky=W)
    exit_label.grid(row=6, column=0, sticky=W)
    exit_button.grid(row=7, column=0, sticky=W)

#main
def main():
    window = Tk()
    config(window)
    window.mainloop()

if __name__ == '__main__':
    main()

'''

1 个答案:

答案 0 :(得分:0)

您正在调用功能,而您真正应该做的就是将功能绑定到命令关键字参数。

错误:

def my_function():
    print("you clicked the button")

button = Button(command=my_function())

右:

def my_function():
    print("you clicked the button")

button = Button(command=my_function)

但是,执行此操作的“正确”方法对您不起作用,因为您的函数接受参数。在这种情况下,您可以创建一个lambda:

def my_function(arg):
    print(arg)

button = Button(command=lambda: my_function("hello world"))