簡體   English   中英

Python 3、Tkinter:退出window時如何退出代碼?

[英]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()

因此,如果 IX 退出 window(不按退出按鈕),我想退出整個程序。 但是,當我這樣做時,因為根仍然處於活動狀態並且只是隱藏,所以代碼不會退出。 然后它將像后台任務或其他東西一樣繼續運行。 那么,當我擊中 X 時如何讓它退出呢? 我已經嘗試將exit()放在ledWin.mainloop()之后,但這不起作用,我不知道為什么。 當我將exit()放在 LightLED function 之后和 MainMenu function 之前時,也會發生這種情況,這是有道理的,因為一切都在 MainMenu ZC1C425268E68385D14AB5074C17ZA 中發生。 但是,有什么地方可以關閉整個程序嗎?

如果這是您的意思,我不是 100%。

# 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM