Python-Tkinter同级窗口交互

2024-09-30 20:18:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我的第一个Python/Tkinter项目已经完成了1000行。是时候给我点提示了。 所以我想先禁用显示布局按钮(灰显)。加载文件后,显示布局处于活动状态。在

def ReadFile()
    #Something Magical Happens
    Layoutbutton.config(state='active')

def DisplayLayout()
    #Draw Great gobs of stuff

def main()
    global Layoutbutton
    #setup root window yada yada yada
    Layoutbutton=Button(root,text="Layout",command=DisplayLayout,underline=0)
    Layoutbutton.place(relx=.5,rely=.85,anchor=CENTER)
    root.bind("l",DisplayLayout)
    root.bind('L',DisplayLayout)
    Layoutbutton.config(state='disabled')

    BrowesButton=Button(root,text="File",command=ReadFile,underline=0)
    BrowesButton.place(relx=.75,rely=.85,anchor=CENTER)
    root.bind("F",ReadFile)
    root.bind('f',ReadFile)

if __name__ == '__main__':

    root=Tk()
    main()

这一切如期而至。DisplayLayout按钮一直显示,直到文件被读取。在

我质疑使用全局布局按钮。我有很多这样的事情发生。 在没有太多全局变量的情况下(因为没有更好的术语)兄弟窗口如何相互通信?在


Tags: 文件textconfigbindmaindefbuttonroot
2条回答

使函数ReadFile接受参数:

def ReadFile(LayoutButton):
    #Something Magical Happens
    LayoutButton.config(state='active')

main内定义一个函数,用LayoutButton调用{}。将出现的ReadFile替换为新函数。在

^{pr2}$

或者,您可以使用lambda代替函数:

wrapper = lambda event=None: ReadFile(Layoutbutton).

或者用类构造程序。在

通过将代码对象化,可以避免使用全局变量。例如,您的示例的不同实现可能是:

def read_file():
    #magic happens    

class MyFrame(object):
    def __init__(self,parent):
        self.parent = parent
        self.layout_button = Button(self.parent,text="Layout",
                             command=self.display_layout,underline=0)
        self.layout_button.place(relx=.5,rely=.85,anchor=CENTER)
        self.parent.bind("l",self.display_layout)
        self.parent.bind('L',self.display_layout)
        self.layout_button.config(state='disabled')
        self.browes_button=Button(self.parent,text="File",
                                  command=self._call_read_file,underline=0)
        self.browes_button.place(relx=.75,rely=.85,anchor=CENTER)
        self.parent.bind("F",self._call_read_file)
        self.parent.bind('f',self._call_read_file)

    def display_layout(self):
        #populate frame etc. 

    def _call_read_file(self):
        read_file()
        self.layout_button.config(state='active')

def main(root):
    frame = MyFrame(root)
    root.mainloop()

if __name__ == "__main__":
    root = Tk()
    main(root)     

这可能是个人偏好,但我发现这样的GUI设计更直观,而且与大量使用全局变量的代码相比,跟踪不需要的行为更容易。通过这种方法,每一帧都保持对其父帧的引用,本质上使所有帧在需要更新时彼此访问。一个完整而相当愚蠢的例子可能是:

^{pr2}$

相关问题 更多 >