How to add a refresh button in Python Tkinter GUI
Many people have been asking how they can add a button so that their tkinter GUI can refresh itself. The first time I wanted to add a refresh button, I thought this was almost impossible because everyone thinks it's not something python has to offer. But I can show you how I managed to add a refresh button into my python code. I am being tempted to think I'm the only one to discover this trick, so if you're going to use it anywhere, don't forget to thank me. :) lol. This is super easy!
Here's how I managed to do it,
1. First create your first tkinter code with a refresh button in it.
Just for the sake of example, let's use the datetime function to see if the time changes everytime we click on the refresh button. If the second changes per click, it means we have successfully created our refresh button.
Save the file as file.pyw
from Tkinter import *
import datetime
now = datetime.datetime.now()
seconds = now.second
window = Tk()
def refresh():
window.destroy()
execfile("file.pyw",globals())
label = Label(window, text = str(seconds))
button = Button(window, text = "Click here to refresh",command = refresh)
label.pack()
button.pack()
window.mainloop()
That's it! Now your tkinter has to refresh itself when you click on it.
Do not hesitate to Comment and ask your questions below and I'll try to answer them all.
Good luck with your coding experience!
Here's how I managed to do it,
1. First create your first tkinter code with a refresh button in it.
Just for the sake of example, let's use the datetime function to see if the time changes everytime we click on the refresh button. If the second changes per click, it means we have successfully created our refresh button.
Save the file as file.pyw
from Tkinter import *
import datetime
now = datetime.datetime.now()
seconds = now.second
window = Tk()
def refresh():
window.destroy()
execfile("file.pyw",globals())
label = Label(window, text = str(seconds))
button = Button(window, text = "Click here to refresh",command = refresh)
label.pack()
button.pack()
window.mainloop()
That's it! Now your tkinter has to refresh itself when you click on it.
Do not hesitate to Comment and ask your questions below and I'll try to answer them all.
Good luck with your coding experience!
6 comments
error comes that execfile is not defined
ReplyDeleteIf you are using python 3. excecfile was removed from python 3.
Deleteinstead of
execfile("./filename")
Use
exec(open("./filename").read())
I can run it once, but the second button press, I received this error:
ReplyDelete_tkinter.TclError: can't invoke "destroy" command: application has been destroyed
Have you get any solution for this? please share..
DeleteI want to refresh the window without the button press. How do I do that?
ReplyDeleteIn case if I package this using pyinstaller, I need to have the python installed and also the .pyw file in called again and again. Is there any other alternative, you can suggest please.
ReplyDelete