如何关闭Tkinter窗口并保留StringVar值?代码运行异常求助
Hey there! Let's tackle those two Tkinter issues you're facing—they're super common, so don't worry, we'll get them sorted out.
Issue 1: Tkinter Window Won’t Close After Selecting Radio Buttons & Clicking OK
First up, that stubborn window refusing to close. The most likely issues are either misplaced quit()/destroy() calls, or a long-running task blocking the main thread from processing the close request. Here's how to fix it:
- Use
destroy()instead ofquit():quit()only stops the mainloop, but doesn’t tear down the window itself.destroy()is the method that properly shuts down the entire widget hierarchy. - Call
destroy()after your logic: Make sure you run all your radio button value-checking code first, then trigger the window close. Avoid infinite loops or heavy computations inside your button action—those will lock up the thread and preventdestroy()from executing.
Example fix for your button action function:
def buttonAction(): # Your existing logic here (read selected radio button value, etc.) global compGDB # We'll come back to this for the second issue compGDB = your_radio_var.get() # Now close the window properly master.destroy()
And structure your main loop like this:
master = Tk() # Set up your radio buttons, OK button, and other UI elements here master.mainloop() # Any code here runs only after the window is closed
Issue 2: compGDB Variable Doesn’t Retain Its Value
This is almost certainly a scope problem. If you’re modifying compGDB inside buttonAction() without declaring it as global, you’re actually creating a local variable that gets discarded once the function finishes. Here are two reliable fixes:
Use the
globalkeyword:
InitializecompGDBoutside your function, then declare it as global insidebuttonAction()to modify the global variable instead of a local one:compGDB = "" # Initialize globally def buttonAction(): global compGDB compGDB = your_radio_var.get() master.destroy()Use a Tkinter variable type:
Instead of a regular Python variable, useStringVar(),IntVar(), or another Tkinter variable. These are tied to the Tkinter app and retain their values even after the window closes:master = Tk() compGDB = StringVar() # Tkinter string variable # Link radio buttons to compGDB Radiobutton(master, text="Option A", variable=compGDB, value="gdb_a").pack() Radiobutton(master, text="Option B", variable=compGDB, value="gdb_b").pack() def buttonAction(): master.destroy() Button(master, text="OK", command=buttonAction).pack() master.mainloop() # Access the value after the window closes print(compGDB.get())
Give these fixes a shot—they should resolve both your window closing and variable persistence issues. If you hit any snags with your specific code, feel free to share more details!
内容的提问来源于stack exchange,提问作者Salty Delgado

