I am wondering on how I can create a restart button that once clicked, can restart the entire script. What I thought was that you destroy the window then un-destroy it but apparently there is no un-destroy function.
I found a way of doing it for a generic python program on this website: https://www.daniweb.com/programming/software-development/code/260268/restart-your-python-program. I wrote an example with a basic tkinter GUI to test it:
import sys
import os
from tkinter import Tk, Label, Button
def restart_program():
"""Restarts the current program.
Note: this function does not return. Any cleanup action (like
saving data) must be done before calling this function."""
python = sys.executable
os.execl(python, python, * sys.argv)
root = Tk()
Label(root, text="Hello World!").pack()
Button(root, text="Restart", command=restart_program).pack()
root.mainloop()
The following solution works as well but is quite harsh, i.e. the entire environment is lost.
# kills the whole application and starts a fresh one
def restart():
root.destroy()
root = Tk()
root.mainloop()
I would Like to Use this Function:-
First of All Import os Module
import os
Then Use this Code:-
# Restarts the Whole Window
def restart():
root.destroy()
os.startfile("main.py")
Or if You want no console behind then Simply Change the extension of the file to .pyw
And Run this Code:-
# Restarts the Whole Window
def restart():
root.destroy()
os.startfile("main.pyw")
Related
I'm using Tkinter to show a login dialog and then run my main logic.
I intend for the following snippet to close the window (finish the main loop of tk) after clicking the button and just print indefinitely (it is wrapped in while True is in order for the whole script to continue executing, which simulates a real program logic).
But instead, the following snippet hangs the window and fails to close in macOS Ventura with Python 3.10:
from time import sleep
from tkinter import Tk, Button
def quit():
root.quit()
root = Tk()
Button(root, text="Quit", command=quit).pack()
root.mainloop()
while True:
sleep(1)
print("Running a program logic...")
I've tried to run a functional version of this code (which fails the same) and a threaded version of it (which just crashes since an NSWindow must be created on the main thread).
I just really can't wrap my head around it!
EDIT: Fully working example
EDIT 2: Clarify the intention of this code
EDIT 3: Even more minimal code
Try this:
from Tkinter import *
def quit():
global root
root.quit()
root = Tk()
while True:
Button(root, text="Quit", command=quit).pack()
root.mainloop()
I have prepared some tk application. It could be really simple like:
from tkinter import *
# create root window
root = Tk()
# root window title and dimension
root.title("Welcome to GeekForGeeks")
# Set geometry (widthxheight)
root.geometry('350x200')
# all widgets will be here
# Execute Tkinter
root.mainloop()
I have using some method to convert the app to the exe file.
What is important,
I'm not using and I cannot do it with pyinstaller py2exe etc. I also cannot use method with changing my app.py to app.pyw.
But my conversion to .exe is working correctly.
The question - is it even possible to hide/disable/resize(reduce the size) of my console window and make the application still working?
I'm not exactly sure how is it done in pyinstaller py2exe etc, so maybe is it possible to do it inside an application?
All right, to solve above problem install:
pip install pywin32
and add code before running your tk gui application:
import win32gui
import win32.lib.win32con as win32con
the_program_to_hide = win32gui.GetForegroundWindow()
win32gui.ShowWindow(the_program_to_hide , win32con.SW_HIDE)
Then you can run the main.py in console, the console will disappear and the gui app will be still visible.
In case when you use pyinstaller etc - you can convert the application without "--noconsole" argument.
When you run the .exe file the console will appear for a second, and disappear. But the gui app will be still visible and usable.
Hope it help somebody somehow :)
I think you should run your script using pythonw.exe instead of python.exe. See .pyw files in python program
Does this help if using Toplevel?
from tkinter import *
root = Tk()
root.title("Main Window")
root.geometry("200x200")
def launch():
global second
second = Toplevel()
second.title("Child Window")
second.geometry("400x400")
def show():
second.deiconify()
def hide():
second.withdraw()
Button(root, text="launch Window", command=launch).pack(pady=10)
Button(root, text="Show", command=show).pack(pady=10)
Button(root, text="Hide", command=hide).pack(pady=10)
root.mainloop()
as I say in the title, when I click on a button (analyse) another windows open and I don't want it. The problems is, in the analyse function, the first line is an import of my tkinter file.
Thanks in advance for any help.
I tried to delete the import and the second windows does not pop up, so I am pretty sure it is the problem. Moreover I need to do this import in the analyse function because I already import the other module in my tkinter file
tkinter file :
import fileb
def analyser():
output=fileb.analyse(name)
fenetre = Tk()
fenetre.geometry("800x500")
label = Label(fenetre, text='Emotion Video')
label.pack()
boutonanalyse=Button(fenetre, text='analyze', command=analyser)
boutonanalyse.pack(side=BOTTOM)
fileb :
def analyse(name):
import tkinter_essais
When you import your Tkinter file, you are running that file. This means that the code is run twice and so you have two windows opened up. A way to bypass this is by putting your tkinter setup into a function, and having that run if it is the main program only using something like this:
import fileb
def analyser():
output=fileb.analyse(name)
def tkSetup():
fenetre = Tk()
fenetre.geometry("800x500")
label = Label(fenetre, text='Emotion Video')
label.pack()
boutonanalyse=Button(fenetre, text='analyze', command=analyser)
boutonanalyse.pack(side=BOTTOM)
if "__name__" == "__main__":
tkSetup()
The if name == main checks if the program is being run originally (best way I can think to describe it) and so it wont be run if you import the file.
I'm making a simple GUI using Python 3.7.3 and tkinter to open and close windows applications. I'm not able to find a way to close a running program using an onscreen button. I need the 'close' button to do something else as well, hence the simply using 'x' button (which is next to the minimize and maximize) won't work for my case.
from tkinter import *
import os, subprocess
root = Tk()
root.geometry("300x300")
def OpenCalc():
app1 = os.startfile("C:\Windows\System32\calc.exe")
def CloseCalc():
os.close(app1)
# or
# os.closefile("C:\Windows\System32\calc.exe")
b1=Button(root, text="Open Calc", command=OpenCalc).pack()
b2=Button(root, text="Close Calc", command=CloseCalc).pack()
root.mainloop()
When running a tkinter program in the standard python idle program the window displays and you are able to interact with it, yet running the same program in pycharm causes the program window to flash up briefly then close.
I'm assuming its to do with the mainloop, what do you need to modify in your code to prevent the program from automatically closing when running in pycharm
An excert from my code follows
from tkinter import *
import tkinter
from tkinter import Text, Tk, ttk
import csv
from csv import DictReader
import sys
import os
class GUI:
def __init__(self, root):
....
def main():
global label
root = Tk()
root.title(" My program")
root.geometry("550x330+600+300")
mycolor = '#%02x%02x%02x' % (39, 39, 39) # background color
root.configure(bg=mycolor)
gui = GUI(root)
main()
Update : After a bit of mucking around, partly due to my code not being the best (rookie), I've managed to get it to work. For anyone interested heres the modification:
from tkinter import *
import csv
from csv import DictReader
import sys
import os
class GUI:
def __init__(self, master):
self.master = master
master.title(" My Programs")
master.geometry("550x330+600+300")
master.iconbitmap('logo.ico')
mycolor = '#%02x%02x%02x' % (39, 39, 39) # background color
master.configure(bg=mycolor)
....... Most of the above is program set up stuff but shown
MAIN CODE HERE
root = Tk()
gui = GUI(root)
root.mainloop()
Works now as expected
Python has a -i startup option which cause Python to enter interactive move when the program finishes, instead of exiting. IDLE executes code as if one entered python -i file.py at the terminal. This allows one to interactively explore the live gui by entering code in the Shell.
From this question and the one referenced by flyingmeatball, it appears that PyCharm does not use or simulate -i. So one must finish a tkinter program with root.mainloop to see anything. Unless one adds a button to quit the mainloop without destroying the application, one will not be able to interact with interactive statements. (Again, this is completely based on what has been posted on SO, as I have no experience with PyCharm.)