簡體   English   中英

Python Tkinter 檢查框架是否存在

[英]Python Tkinter Check if Frame exists

我正在嘗試執行以下操作:

  1. 使用“文件”菜單創建 Tkinter 應用程序。
  2. 文件菜單有 2 個選項,添加和查看。
  3. 添加選項添加一個框架,然后在框架中添加一個標簽小部件(標簽 1)。
  4. 如果我然后從文件菜單中選擇查看選項,它應該打印出框架小部件是否已經存在。

以下是我的嘗試,但我收到錯誤

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

我復制了你的問題。 我得到了下面的代碼,可以在 Linux 上使用 Python3.4。 f需要變成self.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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM