Why a file is empty after writing to it?
When I add print(img_list)
to write_to_file()
I see that this function is executed at start - without clicking button - even before create_img_list()
runs (which creates list) so write_to_file()
writes empty list.
You use command=
incorrectly. It needs function name without ()
(so called "callback") but you run function and you assign its result to command=
. Your code works like
result = _thread.start_new_thread(write_to_file, ()) # it executes function at startbutton = tk.Button(root, text="Click Me", command=result).pack()
but you need
def run_thread_later(): _thread.start_new_thread(write_to_file, ())button = tk.Button(root, text="Click Me", command=run_thread_later).pack()
Eventually you can uses lambda
to create this function directly in command=
button = tk.Button(root, text="Click Me", command=lambda:_thread.start_new_thread(write_to_file, ())).pack()
BTW: you have common mistake
button = Button(...).pack()
which assign None
to variable because pack()
/grid()
/place()
return `None.
If you need access button
later then you have to do it in two lines
button = Button(...)button.pack()
If you don't need access button
later then you can skip `button()
Button(...).pack()