I am trying use object oriented programming style to write the code for a Tkinter app. I want to use a class method to place labels(or other widgets) to the GUI. The code I wrote is adding a character which I don't expect to the GUI. How can I write the initial add_label method so that it does not add the unwanted character. Below is my code and a screenshot. I am new to OOP, so i might be missing something.
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()
I am new to OOP and stil trying to figure out how i can benefit from code reuse in this case. My app has several widgets and functions
What do you expect self.add_label(root)
to do? According to your method definition, it takes text
as argument, so when you say self.add_label(root)
, you are passing root
as text
. And what is root
? It is '.'
, so remove it and it'll be gone.
Though a proper way to do this will be to pass a parent
argument to the method and use that while widget creation:
And the important part is, your instantiating the class
wrong. Keep a reference to it, rather than creating a lot of instances.
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()
Try not to get confused with both the mistakes.
How would I write this class? I don't know the true purpose of this, but I think you can follow something like this:
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.