![](/img/trans.png)
[英]How to label each circle you draw when using the method create_oval() from module tkinter?
[英]Create TKinter label using class method
我正在尝试使用面向 object 的编程风格来编写 Tkinter 应用程序的代码。 我想使用 class 方法将标签(或其他小部件)放置到 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
作为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()
尽量不要混淆这两个错误。
我将如何写这个 class? 我不知道这样做的真正目的,但我认为您可以遵循以下内容:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.