Button press displays label - labels are overlapping

Viewed 45

In my overall project, I am running code very similar to the code below. I am trying to display some text upon a button press. In my overall project, when I click the button, new text renders but it is overlapping the old text rather than deleting the old text and then rendering the new.

How can I display and update text free of overlap upon button press?

My code below after EDIT -> jokeTextBox.config is undefined

class Joke(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent, background="#3a4466")

        jokeTextBox = ttk.Label(self, background="red", foreground="white", )
        jokeTextBox.place(x=250, y=150)
        
    def jokeMode(self):
        global jokeCount
        text = aJokeFunction()
        jokeTextBox.config(text=text,bg="red", fg="white")

1 Answers

How can I display and update text free of overlap upon button press?

Create an empty label after you created the button, then in the jokeMode() function just config the label's text.


joke = Button(text="Joke", command=jokeMode(), background='pink')

This line will call the function jokeMode() only once. So, use command=jokeMode instead.

Here is the complete solution:

.
.
.
def jokeMode():
    text = aJokeFunction()
    #configure the label with new text and other attributes like bg, fg
    jokeTextBox.config(text=text,bg="red", fg="white")


joke = Button(text="Joke", command=jokeMode, background='pink') #use command=jokeMode instead of command=jokeMode()
joke.place(x=75, y=50)
#create an empty label for joke here 
jokeTextBox = Label(ws)
jokeTextBox.place(x=25, y=150)

ws.mainloop()

If using OOP:

class Joke():
    def __init__(self, parent):
        self.myFrame = Frame(parent, background="#3a4466")
        self.myFrame.place(x=75, y=150)

        self.jokeTextBox = Label()
        self.jokeTextBox.place(x=250, y=150)
        
    def jokeMode(self):
        text = aJokeFunction()
        self.jokeTextBox.config(text=text,bg="red", fg="white")


jokeFrame = Joke(ws)
joke = Button(text="Joke", command=jokeFrame.jokeMode, background='pink')
joke.place(x=75, y=50)

ws.mainloop()
Related