简体   繁体   English

Python Tkinter 检查框架是否存在

[英]Python Tkinter Check if Frame exists

I am trying to do the following:我正在尝试执行以下操作:

  1. Create a Tkinter App with a 'File' menu.使用“文件”菜单创建 Tkinter 应用程序。
  2. The File Menu has 2 options, Add and View.文件菜单有 2 个选项,添加和查看。
  3. The Add option adds a Frame and then adds a Label widget (Label 1) in the frame.添加选项添加一个框架,然后在框架中添加一个标签小部件(标签 1)。
  4. If I then select the View option form the file menu, it should print out whether or not a Frame widget already exists.如果我然后从文件菜单中选择查看选项,它应该打印出框架小部件是否已经存在。

Following is my attempt at it, but I receive the error以下是我的尝试,但我收到错误

AttributeError: 'Test' object has no attribute 'tk' AttributeError: 'Test' 对象没有属性 'tk'

when I select the View option, can someone please help point out what I am missing here?当我选择“查看”选项时,有人可以帮我指出我在这里遗漏了什么吗?

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() 

I replicated your problem.我复制了你的问题。 I got the code below to work using Python3.4 on Linux.我得到了下面的代码,可以在 Linux 上使用 Python3.4。 f needs to become self.f. f需要变成self.f。 I named it self.frame.我将其命名为 self.frame。 This enables the frame to be accessed outside of the method it is created in.这使得可以在创建框架的方法之外访问框架。

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()

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

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