How to: tkinter-python to monitor a file, add buttons automatically, and exit cleanly
I had difficulties creating a program that used tkinter and python that allowed a file to be monitored, buttons to be added, and the program to be exited cleanly.
This arose in part from an awkward series of root.mainloop() and Tkinter.Tk() instances that were being generated and could not be exited cleanly even with the following code that should have ended it (this code is overkill – sys.exit alone should kill the program) –if you’re looking to kill Tkinter much of this will do it:
If you’re trying to run processes concurrently with tkinter and it won’t close – the structure is most likely wrong. GTK had tolerated an abuse of the structure – allowing multiple main windows to be generated – tkinter won’t. Though I had originally used threading, most likely improperly as well, this comes with several dangers and wasn’t working and wasn’t necessary for what I was trying to do. The after method allowed the tkinter window and file checking to run seemingly simultaneously.
This post is very helpful in understanding / using `after`:
Basically, for a program to keep checking a file for changes and to reflect those changes in a list of buttons – the normal root = Tkinter.Tk() and root.main() format must be followed within the body. The looping and while statements are accomplished using “after”.
Basically, I used one function that completed once to construct the initial buttons (and they’re placed at the top as new buttons are added below) – makethelistofbuttons(), then each cycle runs refresh() which only adds new buttons.
[In gtk, I had originally attempted (with semi-success) to generate and destroy the list of buttons with each iteration of refresh(). That did not work here.]
The code necessary to create the file checking (seemingly concurrent) to running the tkinter window:
To show how the buttons are read in and generated the complete code is provided below. It may also be worth mentioning that some people have warned against `win.update()` – but it seemed to be integral to getting the program to work.
|All times are GMT -5. The time now is 09:02 AM.|