简体   繁体   English

无法在Tkinter GUI的Entry小部件中显示值

[英]Unable to to show value in Entry widget in Tkinter GUI

In this GUI application, simpleapp is the main window. 在此GUI应用程序中,simpleapp是主窗口。 As part of initializing simpleapp, I am trying to set the home directory for the application, using class setHomeDir to open a window so that I can confirm / set the current working directory. 作为初始化simpleapp的一部分,我试图使用类setHomeDir来打开应用程序的主目录,以打开一个窗口,以便我可以确认/设置当前的工作目录。 To begin with, I am unable to get the current working directory to display in the setHomeDir window ie I am not able to get self.entryVariable.set(home) to work. 首先,我无法在setHomeDir窗口中显示当前工作目录,即无法使self.entryVariable.set(home)工作。

Where am I going wrong here? 我在哪里错了?

import Tkinter, os


class simpleapp(Tkinter.Tk):
    def __init__(self,parent):
        Tkinter.Tk.__init__(self,parent)
        self.geometry('500x300+200+50')
        self.home_dir=os.getcwd()
        self.t=setHomeDir(parent=self, home=self.home_dir)



class setHomeDir(Tkinter.Tk):
    def __init__(self,parent, home):
        Tkinter.Tk.__init__(self)
        self.parent = parent
        self.geometry('500x100+200+50')
        self.title('Set Home Directory')

        self.grid()

        #Input Box
        self.entryVariable = Tkinter.StringVar()
        self.entry = Tkinter.Entry(self, textvariable=self.entryVariable)
        self.entryVariable.set(home) 
        self.entry.grid(column=0,row=0,sticky='EW')


        self.grid_columnconfigure(0,weight=1)
        self.resizable(True,False)


if __name__ == "__main__":
    app = simpleapp(None)
    app.title('Main Window')
    app.mainloop()

Also you do not want multiple instances of Tk(). 另外,您也不需要Tk()的多个实例。 It gets confused when there is more than one instance, so use a Toplevel instead. 当存在多个实例时,它会造成混乱,因此请使用顶级。

import Tkinter, os

class SimpleApp():
    def __init__(self,parent):
        self.parent = parent
        self.parent.geometry('500x300+200+50')
        self.parent.title('Main Window')
        self.home_dir=os.getcwd()

        ## pass same Tkinter instance to the class
        SetHomeDir(parent=self.parent, home=self.home_dir)

class SetHomeDir():
    def __init__(self,parent, home):
        self.parent = parent
        self.top=Tkinter.Toplevel(self.parent)
        self.top.geometry('500x100+200+500')
        self.top.title('Set Home Directory')

        #Input Box
        self.entryVariable = Tkinter.StringVar()
        self.entry = Tkinter.Entry(self.top, textvariable=self.entryVariable)
        self.entryVariable.set(home) 
        self.entry.grid(column=0,row=0,sticky='EW')
        self.entry.focus_set()

        self.top.grid_columnconfigure(0,weight=1)
        self.top.resizable(True,False)

if __name__ == "__main__":
    root=Tkinter.Tk()
    app = SimpleApp(root)
    root.mainloop()

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

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