代码之家  ›  专栏  ›  技术社区  ›  babsdoc

Python Tkinter检查帧是否存在

  •  1
  • babsdoc  · 技术社区  · 7 年前

    我正在努力做到以下几点:

    1. “文件”菜单有两个选项,“添加”和“查看”。
    2. 添加选项添加一个框架,然后在框架中添加一个标签小部件(标签1)。
    3. 如果我随后从文件菜单中选择查看选项,它应该打印出框架小部件是否已经存在。

    下面是我的尝试,但我收到了错误

    AttributeError:“Test”对象没有属性“tk”

    from tkinter import Tk, Menu, Label, Frame
    class Test():
        def __init__(self):
            self.gui = Tk()
            self.gui.geometry("600x400")
    
            menu = Menu(self.gui)
            new_item1 = Menu(menu)
            menu.add_cascade(label='File', menu=new_item1)
            new_item1.add_command(label='Add', command=self.addlbl)
            new_item1.add_command(label='View', command=self.viewlbl)    
    
            self.gui.config(menu=menu)
            self.gui.mainloop()
    
        def addlbl(self):
            f=Frame()
            f.pack()
            lbl1 = Label(f, text="Label 1").grid(row=0, column=0)
    
        def viewlbl(self):
            print(Frame.winfo_exists(self))      
    
    T=Test() 
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Oppy    7 年前

    我重复了你的问题。我得到了下面的代码,可以在Linux上使用Python3.4。f需要变得自我。我把它命名为self.frame。这使得可以在创建框架的方法之外访问框架。

    from tkinter import Tk, Menu, Label, Frame
    class Test():
    
    def __init__(self):
        self.gui = Tk()
        self.gui.geometry("600x400")
        menu = Menu(self.gui)
        new_item1 = Menu(menu)
        menu.add_cascade(label='File', menu=new_item1)
        new_item1.add_command(label='Add', command=self.addlbl)
        new_item1.add_command(label='View', command=self.viewlbl)    
        self.gui.config(menu=menu)
        self.gui.mainloop()
    
    def addlbl(self):
        self.frame = Frame(self.gui)
        self.frame.pack()
        lbl1 = Label(self.frame, text="Label 1")
        lbl1.grid(row=0, column=0)
    
    def viewlbl(self):
        print('frame exists {}'.format(self.frame.winfo_exists()))
    
    
    T=Test()