简体   繁体   English

如何关闭 Tkinter window 并保留 StringVar 值?

[英]How do I close a Tkinter window and retain a StringVar value?

I am having a couple issues with the following code:我在使用以下代码时遇到了一些问题:

  1. After the radio button is selected and the OK button is selected, the Tkinter window does not close.选择单选按钮和选择确定按钮后,Tkinter window 没有关闭。 I have tried various methods to close the Tkinter window - quit() and destroy() both inside buttonAction() and after master.mainloop() - but neither has worked.我尝试了各种方法来关闭 Tkinter window - quit()destroy()都在buttonAction()内部和master.mainloop()之后 - 但都没有用。 The code will run endlessly and the window does not close.该代码将无休止地运行,并且 window 不会关闭。
  2. The compGDB variable assignment is not retained after the code is run.代码运行后不会保留compGDB变量赋值。 At this point, I'm wondering if the compGDB variable isn't retaining simply because the destroy/quit code failure.在这一点上,我想知道compGDB变量是否仅仅因为销毁/退出代码失败而没有保留。

import Tkinter, getpass
username = getpass.getuser()

def buttonAction():
    compGDB = choice.get()
    print compGDB
    #master.quit()
    #master.destroy()

vwrMinGDB = "C:\\Users\\" + username + "\\Desktop\\ViewerAttribution\\Viewer_minimum.gdb"
fullGDB = "C:\\Users\\" + username + "\\Desktop\\ViewerAttribution\\Full_geodatabase.gdb"

master = Tkinter.Tk()
master.title("Schema comparison")
master.geometry("250x100")

choice = Tkinter.StringVar()
choice.set(vwrMinGDB)

chooseOption = Tkinter.Label(master, text="Slect geodatabase for schema comparison")
rButton1 = Tkinter.Radiobutton(master, text="Viewer Minimum Attribution", variable=choice, value=vwrMinGDB)
rButton2 = Tkinter.Radiobutton(master, text="Full Geodatabase Attribution", variable=choice, value=fullGDB)
confirmButton = Tkinter.Button(master, text="OK", command=buttonAction)

chooseOption.grid(column="1", row="0")
rButton1.grid(column="1", row="1")
rButton2.grid(column="1", row="2")
confirmButton.grid(column="1", row="3")

master.mainloop()
#master.quit()
#master.destroy()

Thanks, y'all!谢谢大家!

I cannot reproduce your first issue. 我无法重印您的第一期。 You can quit() by calling master.quit() within def buttonAction(): , there should be something else missing. 您可以通过在def buttonAction():调用master.quit()quit() ,否则应该缺少其他内容。

Your second issue though, it is because compGDB is locally created within the function buttonAction , so once the function is done the attribute ceases to be. 但是,您的第二个问题是,因为compGDB function buttonAction本地创建的,所以一旦完成该功能,该属性便不再存在。

While the better advice is to rebuild your code as a class and define compGDB as an instance/class attribute (so you can recall it as long as the class instance is still in memory), you can see it can be a bit of work. 虽然更好的建议是将代码重建为一个class并将compGDB定义为实例/类属性 (因此,只要类实例仍在内存中,您就可以调用它),但是您可以看到它有些工作。 An easy workaround (IMO not best practice) would be: 一个简单的解决方法(IMO不是最佳实践)是:

compGDB = ''

def buttonAction():
    global compGDB
    compGDB = choice.get()
    master.quit()

So that this way, the global attribute compGDB is still retained and you can recall it anywhere even after master.mainloop() . 这样, 全局属性compGDB仍然保留,即使在master.mainloop()之后,您也可以在任何地方调用它。

But again, consider using an OOP approach for your tkinter if you have use for the information afterwards. 但是同样,如果以后使用了信息,请考虑对您的tkinter使用OOP方法。 It'll help maintain your namespace easier especially for complex scripts. 这将有助于更轻松地维护名称空间,尤其是对于复杂的脚本。

For the second issue: Retain a variable after tkinter window is closed with destroy() I implemented the OOP approach r.ook suggested.对于第二个问题:在使用destroy()关闭tkinter window 后保留变量 我实施了建议的 OOP 方法 r.ook。 I took some furhter inspiration for this approach from https://www.pythontutorial.net/tkinter/tkinter-object-oriented-window/ .我从https://www.pythontutorial.net/tkinter/tkinter-object-oriented-window/中获得了对这种方法的进一步启发。

In my example a filepath is retained after the window is closed, but it could be any variable.在我的示例中,文件路径在 window 关闭后保留,但它可以是任何变量。

from fileinput import filename
import tkinter as tk
from tkinter import filedialog


class tkApp(tk.Tk):
    def __init__(self):
        super().__init__()
        
        self.filename = ""

        # Config root window
        self.title('Select a file to plot.')

        # Buttons
        self.my_btn = tk.Button(self, text="Select File", command=self.open_fileselect).pack()
        self.my_btn2 = tk.Button(self, text="Quit", command=self.destroy).pack()

        self.tk.mainloop()

    def open_fileselect(self):
        self.filename = filedialog.askopenfilename(initialdir=r'C:\Users\some_dir',
                title="Select A File", filetypes=(("excel sheets", "*.xlsx"),("all files", "*.*")))
        self.myLabel= tk.Label(self, text=self.filename).pack()
        self.my_img_label= tk.Label(self,text="Test").pack()
        self.data_filepath = self.filename

# Create class instance. This will automatically run tkinter, since the mainloop call is included inside the class.
my_App = tkApp()

# Retrieve the variable from the class instance
print(my_App.filename)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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