首页 > 解决方案 > 使用类方法创建 TKinter 标签

问题描述

我正在尝试使用面向对象的编程风格来编写 Tkinter 应用程序的代码。我想使用类方法将标签(或其他小部件)放置到 GUI。我编写的代码正在向 GUI 添加一个我不希望的字符。如何编写初始add_label 方法,使其不添加不需要的字符。下面是我的代码和截图。我是 OOP 的新手,所以我可能会遗漏一些东西。

from tkinter import *
class App:
    def __init__(self, parent):
        self.widgets(root)
        self.add_label(root)

    def widgets(self, app):
        self.title = Label(app, text= 'LABEL UP').pack()
        self.btn = Button(app, text = 'BUTTON').pack()
    def add_label(self, text):
        Label(text= text).pack()

root = Tk()
App(root)
App.add_label(root, 'LABEL_1')
App.add_label(root,'LABEL_2')
root.mainloop()

在此处输入图像描述 我是 OOP 的新手,仍然试图弄清楚在这种情况下如何从代码重用中受益。我的应用程序有几个小部件和功能

标签: pythonooptkinter

解决方案


你期望self.add_label(root)做什么?根据您的方法定义,它需要text作为参数,所以当您说 时self.add_label(root),您传递root的是 as text。什么是root?它是'.',所以删除它,它就会消失。

虽然这样做的正确方法是将parent参数传递给方法并在创建小部件时使用它:

重要的是,您实例化了class错误。保留对它的引用,而不是创建很多实例。

from tkinter import *

class App:
    def __init__(self, parent):
        self.widgets(root)

    def widgets(self, app):
        self.title = Label(app, text= 'LABEL UP').pack()
        self.btn = Button(app, text = 'BUTTON').pack()
    
    def add_label(self, parent, text):
        Label(parent,text= text).pack()

root = Tk()

app = App(root)
app.add_label(root, 'LABEL_1')
app.add_label(root,'LABEL_2')

root.mainloop()

尽量不要混淆这两个错误。

我将如何写这门课?我不知道这样做的真正目的,但我认为您可以遵循以下内容:

from tkinter import *

class App:
    def __init__(self, parent):
        self.parent = parent
        
        self.title = Label(self.parent, text='LABEL UP')
        self.title.pack()

        self.entry = Entry(self.parent)
        self.entry.pack()

        self.btn = Button(self.parent, text='BUTTON')
        # Compliance with PEP8
        self.btn.config(command=lambda: self.add_label(self.entry.get())) 
        self.btn.pack()

    def add_label(self, text):
        Label(self.parent, text=text).pack()

    def start(self):
        self.parent.mainloop()

root = Tk()

app = App(root)
app.start()

推荐阅读