-1

I'm using this question as a reference for how to structure a Tkinter class, but when I run the program and answer the pop-up dialog I create, the root window automatically closes.

from tkinter import *
from tkinter import simpledialog as sd 
from datetime import datetime, date
import time
import pyowm as owm

# access API key
owm = foo
COUNTRY = 'US'

class App(Tk):
    def __init__(self):
        # create window and set size
        self.root = Tk()
        self.root.title("Weatherman")
        self.root.geometry('700x200')

        # get location
        self.location = sd.askstring("Input","What's your location? Format as City, Country",parent=self.root)
        self.location.strip()

        # get date and time 
        current_date = StringVar()
        current_date.set(date.today)

        # debug label to check variable
        self.test_label = Label(self.root,text=current_date.get())
        self.test_label.pack()

def main():
    app = App()
    app.mainloop

if __name__ == '__main__':
    main()
John Allison
  • 356
  • 1
  • 3
  • 16
  • Read [Why are multiple instances of Tk discouraged?](https://stackoverflow.com/questions/48045401/why-are-multiple-instances-of-tk-discouraged) – stovfl Aug 21 '19 at 21:28

1 Answers1

0

As mentioned in the comments, you should only have one instance of tk.Tk() running at any one time.
You need to decide whether you want your app to inherit from tk.Tk, or if it will be composed of a root instance of tk.Tk()...

Further, asking for user input from the __init__ method is somewhat an anti-pattern. I refactored this in a separate function.

Last, the self-actuating powers of tk.Stringvar are fully expressed when you assign it to a widget textvariable.

The following example of uses inheritance from tk.Tk:

import tkinter as tk
from tkinter import simpledialog
from datetime import date


class App(tk.Tk):
    def __init__(self, location=None):
        super().__init__()
        self.title("Weatherman")
        self.geometry('700x200')
        current_date = tk.StringVar()
        current_date.set(str(date.today()))
        self.location = None

        self.test_label = tk.Label(self, textvariable=current_date)
        self.test_label.pack()


def get_location(app):
    location = tk.simpledialog.askstring("Input","What's your location? Format as City, Country")
    return location.strip()


def main():
    app = App()
    app.location = get_location(app)
    app.mainloop()


if __name__ == '__main__':
    main()
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80