我正在尝试进行tkinter练习,但出现此错误。基本上,当代码首次运行时,该命令立即运行,但是,仅在按下按钮时运行。
from tkinter import *
try:
def the_function_that_makes_a_new_label_for_the_main_window():
the_second_label_for_the_first_window_that_the_function_runs.configure(text='pleese work I beg')
the_main_window_that_will_show_up_when_the_code_is_run=Tk()
the_main_label_for_the_first_window_that_prints_hellow_world=Label(the_main_window_that_will_show_up_when_the_code_is_run, text='hellow world',font=('comicsans', 70))
the_second_label_for_the_first_window_that_the_function_runs=Label(the_main_window_that_will_show_up_when_the_code_is_run, text='hellow world', font=('comicsans', 70))
the_main_button_for_the_first_window=Button(the_main_window_that_will_show_up_when_the_code_is_run, text='click here', command=the_function_that_makes_a_new_label_for_the_main_window())
the_main_label_for_the_first_window_that_prints_hellow_world.pack()
the_second_label_for_the_first_window_that_the_function_runs.pack()
the_main_window_that_will_show_up_when_the_code_is_run.configure(bg='blue')
the_main_button_for_the_first_window.pack()
the_main_window_that_will_show_up_when_the_code_is_run.mainloop()
except:
print('AN ERRORR HAS OCCURED!')
1
投票
问题是,当您为按钮调用命令后,您有括号(括号)。我运行了它,它运行良好:
from tkinter import *
try:
def the_function_that_makes_a_new_label_for_the_main_window():
the_second_label_for_the_first_window_that_the_function_runs.configure(text='pleese work i beg')
the_main_window_that_will_show_up_when_the_code_is_run=Tk()
the_main_label_for_the_first_window_that_prints_hellow_world=Label(the_main_window_that_will_show_up_when_the_code_is_run, text='hellow world',font=('comicsans', 70))
the_second_label_for_the_first_window_that_the_function_runs=Label(the_main_window_that_will_show_up_when_the_code_is_run, text='hellow world', font=('comicsans', 70))
the_main_button_for_the_first_window=Button(the_main_window_that_will_show_up_when_the_code_is_run, text='click here', command=the_function_that_makes_a_new_label_for_the_main_window())
the_main_label_for_the_first_window_that_prints_hellow_world.pack()
the_second_label_for_the_first_window_that_the_function_runs.pack()
the_main_window_that_will_show_up_when_the_code_is_run.configure(bg='blue')
the_main_button_for_the_first_window.pack()
the_main_window_that_will_show_up_when_the_code_is_run.mainloop()
except:
print('AN ERRORR HAS OCCURED!')
此外,在声明变量名时,请尽量使其简短而精确,这在编写更长的程序时也将有所帮助,而且更容易使人眼前一亮。希望对您有帮助。
0
投票
发生这种情况是因为您正在调用该函数:
the_main_button_for_the_first_window=Button(the_main_window_that_will_show_up_when_the_code_is_run, text='click here', command=the_function_that_makes_a_new_label_for_the_main_window())
将其更改为:
the_main_button_for_the_first_window=Button(the_main_window_that_will_show_up_when_the_code_is_run, text='click here', command=the_function_that_makes_a_new_label_for_the_main_window)
这无关紧要,但实际上,要使变量名简短明了,也不要让行太长!