Search code examples
pythonfunctionuser-interfacecommandexit

Command to halt / stop python code running


I've designed two GUIs. One GUI opens when the python code is run and the second GUI opens when the user exits the first one.

The first GUI is to inform the user of an issue with the second GUI and contains a solution to fix the issue if it happens. I added the first GUI in after I completed the second one and realised an issue with the design which can't be fixed.

Right now, the first GUI has an 'Understand and Accept' button on it. I want to add a button which stops the python code running.

I've created a very basic version of what I mean below. I've cut out the unnecessary bits and renamed others to better be able to explain, so that's why the grid values don't match up.

import tkinter as tk
from tkinter import *

def runwarningwindow():
    #This is the first GUI which opens warning tab
    warningscreen = Tk()
    warningscreen.resizable(width=False, height=False)
    warningscreen.title("First Window - Trial Warning Window")

    #This is the Warning message
    warningmessage = Label(warningscreen, text="Warning Message")
    warningmessage.grid(row=1, column=0)
    #This is the Accept Button
    warningunderstoodbutton = tk.Button(warningscreen, text='Understand and Accept', command=warningscreen.destroy)
    warningunderstoodbutton.grid(row=3, column=0)
    rejectedButton= tk.Button(warningscreen, text='Stop')
    rejectedButton.grid(row=4, column=0)
    warningscreen.mainloop()

runwarningwindow()

trialGUI = Tk()
trialGUI.geometry('710x320')
trialGUI.title("Second GUI - Test GUI")
trialGUI.mainloop()

I know one of the possible solutions is to turn the 'trialGUI' into

def runtrailGUI():
    trialGUI = Tk()
    trialGUI.geometry('710x320')
    trialGUI.title("Second GUI - Test GUI")
    trialGUI.mainloop()

and then make the 'Understand and Accept' button run it, but this is a solution I'm trying to avoid. The code for the second GUI is over 3000 lines (and counting, I'm still adding more to it), so I'm looking for another solution. Is there a command to stop python code being run?


Solution

  • When you want to stop the program, you can use the following command:

    raise SystemExit