Tkinter displaying data from database to new window

Viewed 472

I'm making a management system with a function to view the database. I want to make it where a new window will pop up displaying the database when the user clicks the "view list" button. I'm saving the "list" function as a new .py file and i'm calling it using the code below in the main file

def listCustomer():
call(["python", "list.py"])

However, I can't seem to make the data appear on the new window as everytime the new window appears its an empty window. Can anyone tell me what I did wrong? I'll attach my code for the list.py file below

from tkinter import *
from PIL import ImageTk,Image
import sqlite3

root = Tk()


def list():
    #Create database
    connect = sqlite3.connect("hmsdata.db")
    #Create cursor
    c = connect.cursor()

    #List database
    c.execute("SELECT *, oid FROM details")
    data = c.fetchall()
    showData=''
    for data in details:
        showData += str(data)+"\n"

    dataLabel = Label(root, text=showData)
    dataLabel.grid(row=0, column=0)

    #Commit changes
    connect.commit()
    #Close connection
    connect.close()

This is what happens when I click the "View Customer" Button, it does not display anything

1 Answers

You could use normal way - import list - and later execute list.list() . This way you should have better control on windows.

But it needs to use Toplevel to create second window.

Minimal working example.

main.py

import tkinter as tk  # PEP8: `import *` is not preferred
import list as ls     # `list` is use to create list - don't use this name

# --- functions ---

def on_click():
    # run method `list()` from file `list`
    ls.list()

# --- main ---

root = tk.Tk()

button = tk.Button(root, text='Second', command=on_click)
button.pack()

root.mainloop()

list.py

import tkinter as tk  # PEP8: `import *` is not preferred

def list():
    second = tk.Toplevel()  # create inside function

    dataLabel = tk.Label(second, text="Hello World")
    dataLabel.grid(row=0, column=0)

BTW: In your version you probably forgot to execute list()


EDIT:

Version which check if window is not open already (main.py is the same)

list.py

import tkinter as tk  # PEP8: `import *` is not preferred

second = None  # to control if window is open

def on_close():
    global second
    
    second.destroy()
    second = None  # to control if window is open
    
def list():
    global second
    
    if second: # if second is not None:
        print('Window already open')
    else:
        second = tk.Toplevel()

        dataLabel = tk.Label(second, text="Hello World")
        dataLabel.grid(row=0, column=0)

        button = tk.Button(second, text='Close', command=on_close)
        button.grid(row=1, column=0)
Related