Search code examples
pythontkinterwindow

How to close the empty tkinter window that pops up when I run my code


I am trying to create a tkinter gui that performs a certain calculation. I create a window to ask for input to do the calculations. However, each time I run my code 2 windows pop up instead of one. Is there a way to automatically close the blank window when I run my code such that the user would only see the window that asks for input.

For simplicity I changed all buttons to close the applications.

import numpy as np
import pandas as pd
from datetime import datetime
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.messagebox
import blpapi
import pdblp
con = pdblp.BCon(timeout=5000)
con.start()

s= ttk.Style()
s.theme_use('xpnative')


root =tk.Tk()

root.title("Vega Requirement Application")
root.geometry("600x400")

ticker_var= tk.StringVar()
volume_var= tk.StringVar()

def close():
    root.destroy()

def clear_all():
    root.destroy()

def vega_calculation():  
    root.destroy()

ticker_label = ttk.Label(root, text='Bloomberg Ticker:',font=('calibre',10,'normal'))
ticker_entry = ttk.Entry(root, textvariable = ticker_var,font=('calibre',10,'normal'))
volume_label = ttk.Label(root, text='Volume:',font=('calibre',10,'normal'))
volume_entry = ttk.Entry(root, textvariable = volume_var,font=('calibre',10,'normal'))

run_btn = ttk.Button(root, text = 'Calculate', command = vega_calculation, width = 13)
close_btn = ttk.Button(root, text= 'Close App', command = close, width =13)
clear_btn = ttk.Button(root, text= 'Clear table', command = clear_all, width=13)



ticker_label.grid(row=0,column=0)
ticker_entry.grid(row=0,column=1)
volume_label.grid(row=1,column=0)
volume_entry.grid(row=1,column=1)
run_btn.grid(row=0,column=2)
close_btn.grid(row=1, column=2)
clear_btn.grid(row=0, column =4)

root.mainloop()

Solution

  • The following two lines will create an instance of Tk() because there is no instance of Tk() when they are executed:

    s = ttk.Style()  # create an instance of Tk() if there is none
    s.theme_use('xpnative')
    

    Move the two lines to after root = tk.Tk() so that it uses the already created instance of Tk():

    root = tk.Tk()
    
    s = ttk.Style()  # use existing instance of Tk(), root
    s.theme_use('xpnative')