Search code examples
pythontkinterttkbootstrap

Why are there 2 windows on my app? I'm using ttkbootstrap


I'm creating a small app that just gets jokes from an API using ttkbootstrap. The problem is there are 2 windows showing when I run the app. Anyone know what I'm doing wrong?

Here's the code:

import requests
import ttkbootstrap as tb
from ttkbootstrap.constants import *

def get_joke():
    url = "https://icanhazdadjoke.com"
    headers = {'Accept': 'application/json'}
    joke_time = requests.get(url, headers=headers).json().get('joke')
    label.config(text=joke_time)
    print(joke_time)

label = tb.Label(text="", font=("Poppins", 16), bootstyle='default')
label.pack(padx=5, pady=10)
btn = tb.Button(text="Get Joke!", command=get_joke)
btn.pack(padx=5, pady=10)

if __name__ == '__main__':
    app  = tb.Window(themename='darkly')
    app.title('Joke App')
    app.geometry('1280x900')
    app.mainloop()

Here is a screenshot of what's happening double window on tkinter ttkbootstrap


Solution

  • You forgot to add a master to your label and button. Example:

    import requests
    import ttkbootstrap as tb
    from ttkbootstrap.constants import *
    
    def get_joke(label):
        url = "https://icanhazdadjoke.com"
        headers = {'Accept': 'application/json'}
        joke_time = requests.get(url, headers=headers).json().get('joke')
        label.config(text=joke_time)
        print(joke_time)
    
    def start(master) -> None:
        label = tb.Label(master, text="", font=("Poppins", 16), bootstyle='default')
        label.pack(padx=5, pady=10)
        btn = tb.Button(master, text="Get Joke!", command=get_joke(label))
        btn.pack(padx=5, pady=10)
    
    if __name__ == '__main__':
        app  = tb.Window(themename='darkly')
        app.title('Joke App')
        app.geometry('1280x900')
        start(app)
        app.mainloop()
    

    Result:

    enter image description here

    Edit:

    If you want to button to actually work, then you need to use lambda and a text variable for the label, like so:

    import requests
    import ttkbootstrap as tb
    from ttkbootstrap.constants import *
    
    def get_joke(label_text):
        url = "https://icanhazdadjoke.com"
        headers = {'Accept': 'application/json'}
        joke_time = requests.get(url, headers=headers).json().get('joke')
        label_text.set(joke_time)
    
    def start(master) -> None:
        label_text = tb.StringVar()
        label = tb.Label(master, textvariable=label_text, font=("Poppins", 16), bootstyle='default')
        label.pack(padx=5, pady=10)
        btn = tb.Button(master, text="Get Joke!", command=lambda: get_joke(label_text))
        btn.pack(padx=5, pady=10)
    
    if __name__ == '__main__':
        app  = tb.Window(themename='darkly')
        app.title('Joke App')
        app.geometry('1280x900')
        start(app)
        app.mainloop()