Oct-23-2019, 01:26 PM
I am building a program that makes a SELECT on my database on my local machine. In this program, I have a menu, and in it, I created a function called SELECT. However, when I select this option again, it creates a new Label just below it, and I just want to update the Label. Below are the ScreenShots of the program and the source code. I was wondering if anyone could help me solve this problem. Thank you!
![[Image: 6LpABkd.png]](https://i.imgur.com/6LpABkd.png)
![[Image: ylbpBQW.png]](https://i.imgur.com/ylbpBQW.png)
![[Image: MJ3Zbds.png]](https://i.imgur.com/MJ3Zbds.png)
![[Image: 6LpABkd.png]](https://i.imgur.com/6LpABkd.png)
![[Image: ylbpBQW.png]](https://i.imgur.com/ylbpBQW.png)
![[Image: MJ3Zbds.png]](https://i.imgur.com/MJ3Zbds.png)
from tkinter import *
import psycopg2 # LIBRARY FOR CONNECT TO THE POSGRESQL DB
root = Tk()
root.geometry('1000x500')
menubar = Menu(root)
con = psycopg2.connect( # LOCAL POSTGRESQL DB CONNECTION
host="localhost",
database="escola",
user="postgres",
password=248657
)
def select():
v = StringVar()
cur = con.cursor() # CREATING A CURSOR
cur.execute("SELECT id, nome, dt_nasc, nome_mae, nome_pai FROM alunos") # QUERY
rows = cur.fetchall()
separator = '+----+-----------------------------+--------------------+-----------------------------+-----------------------------+'
prep_string = ''''''
prep_string = '''{}{}\n'''.format(prep_string, separator)
prep_string = '''{}{}\n'''.format(prep_string, '|ID'.ljust(5) + '| Nome'.ljust(30) + '| Data de Nascimento |'.ljust(
21) + ' Nome da Mãe'.ljust(29) + '| Nome do Pai'.ljust(30) + '|')
prep_string = '''{}{}\n'''.format(prep_string, separator)
for r in rows:
prep_string = '''{}{}\n'''.format(prep_string,
f'|{r[0]}'.ljust(5) + f'| {r[1]}'.ljust(30) + f'| {r[2]}'.ljust(
21) + f'| {r[3]}'.ljust(30) + f'| {r[4]}'.ljust(30) + '|')
prep_string = '''{}{}\n'''.format(prep_string, separator)
v.set(prep_string)
cur.close()
box = Label(root, textvariable=v, font='TkFixedFont').pack() # THE LABEL
# THE MENU
file = Menu(menubar, tearoff=0)
menubar.add_cascade(label="Principal", menu=file)
file.add_command(label="SELECT", command=select)
file.add_command(label="Exit", command=root.quit)
root.config(menu=menubar)
root.mainloop()
