python - 使用类方法创建 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()
解决方案
你期望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()
推荐阅读
- spring-boot-jpa - 如何将地图集合作为 jpa 查询返回
- google-sheets - 仅返回连接公式的值
- asp.net-mvc - 未捕获的类型错误:无法在 bootstrap.min.js:6 处读取 util.js:68 处未定义的属性“fn”
- python-3.x - Python:使用导入时找不到对类的引用
- python - 如何在txt文件中找到一个单词
- r - 就地重新编码多个值
- vb.net - VB.Net 如何以编程方式添加控件和事件处理程序
- xcode - Xcode 10.2.1 性能问题
- powershell - 使用字符串拆分而不保留分隔符
- python - 如何读取大文件txt,然后制作数据框