简体   繁体   中英

Python 3, Tkinter: How do I exit the code when I exit out of the window?

root = Tk()

icon2 = PhotoImage(file="Arduino UI Icon 2.png")

root.iconphoto(True, icon2)

def LightLED():
    global root
    root.withdraw()

    ledWin = Tk()
    ledWin.resizable(False, False)
    ledWin.title("Arduino UI")
    ledWin.geometry('1280x720')

    pinMess = Message(ledWin, text="Enter Pin Number: ", width=200, font=("Arial", 10))
    pinMess.place(x=0, y=10)

    pinEntry = Entry(ledWin, width=3)
    pinEntry.place(x=40, y=35)

    def SetPin():
        global led, pin

        try:
            pin = pinEntry.get()
            led = board.get_pin("d:" + pin + ":p")
        except:
            pass

    pinBut = Button(ledWin, text="Set Pin", width=10, height=1, font=("Arial", 10), 
command=SetPin)
    pinBut.place(x=70, y=32)

    def LEDbOn():
        led.write(1)

    def LEDbOff():
        led.write(0)

    def LEDQuit():
        global root
        led.write(0)

        ledWin.destroy()
        root.deiconify()

    ledbOn = Button(ledWin, text="Start", command=LEDbOn, width=8, height=1)
    ledbOn.place(x=170, y=30)

    ledbOff = Button(ledWin, text="Stop", command=LEDbOff)
    ledbOff.place(x=185, y=70)

    ledwinQuit = Button(ledWin, text="Exit", command=LEDQuit)
    ledwinQuit.place(x=187, y=110)

    ledWin.mainloop()

def MainMenu():
    root.resizable(False, False)
    root.title("Arduino UI")
    root.geometry('1280x720')

    menubar = Menu(root)
    root.config(menu=menubar)

    fileMenu = Menu(menubar, tearoff=0)
    subMenu = Menu(fileMenu, tearoff=0)
    menubar.add_cascade(label="Programs", menu=fileMenu)

    fileMenu.add_command(label="Light LED", command=LightLED)

    root.mainloop()

if __name__ == "__main__":
    MainMenu()

exit()

So, I want to exit out of the entire program if IX out of the window (Without pressing the Exit button). But, when I do that, because the root is still active and only hidden, the code will not exit out. Then it will keep running as like a background task or something. So, how do I make it exit when I hit the X? I have already tried to put the exit() after the ledWin.mainloop() , but that doesn't work, and I have no idea why. It also happens when I put the exit() after the LightLED function and before the MainMenu function, which makes sense because everything is happening within the MainMenu function. But, is there any place to put it that will close the entire program?

I am not 100% if this is what you meant you are trying to do.

# import required module 
from tkinter import *
  
# create object
root = Tk()
  
# create button to implement destroy()
Button(root, text="Quit", command=root.destroy).pack()
  
root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM