Home > Mobile >  Can I prevent the tkinter window from opening when prompting the user with a messagebox?
Can I prevent the tkinter window from opening when prompting the user with a messagebox?

Time:10-06

I made a simple example of the issue I am having. I want to prevent the little square tkinter box with the feather and the title tk from popping up when I bring up a messagebox. Sample code below:

import tkinter as tk
from tkinter import messagebox
import pyodbc

class app1(tk.Tk):
    def __init__(self, *args, **kwargs):
        try:
            tk.Tk.__init__(self, *args, **kwargs)
            connection(self)
            self.cursor.execute('SELECT 1')
        except:
            messagebox.showerror(title='Error', message='An error has occured')


class connection():
    def __init__(self, controller):
        try:
            driver_name = ''
            driver_names = [x for x in pyodbc.drivers() if x.endswith(' for SQL Server')]
            if driver_names:
                driver_name = driver_names[0]

            controller.conn = pyodbc.connect(f'Driver={driver_name}; '
                                       'Server=1.1.1.1\TEST,9400;'
                                       'Database=Test;'
                                       'pool_pre_ping=True;' 
                                       'pool_recycle=3600;'
                                       'UID=test;'
                                       'PWD=test;',
                                        timeout=1
                                  )
            controller.cursor = controller.conn.cursor()
        except:
            messagebox.showerror(title='Error', message='An error has occured')


if __name__ == "__main__":
    app = app1()
    app.mainloop()

CodePudding user response:

You can withdraw the root window with self.withdraw() during __init__of the app1 class. If you want to show the root window again, use self.deiconify():

class app1(tk.Tk):
    def __init__(self, *args, **kwargs):
        try:
            tk.Tk.__init__(self, *args, **kwargs)
            self.withdraw()  # withdraw root window
            connection(self)
            self.cursor.execute('SELECT 1')
        except:
            messagebox.showerror(title='Error', message='An error has occured')
            self.deiconify()  # show root window
  • Related