delete a frame and update the index - python

I generate frames according to the selection made on a treeview. this treeview is connected to a sqllite3 type database. I have a concern which is the following (I hope to be clear in my explanations). once the selections are made (example 3 selections), I delete one of them. Then I make a new selection. the added frame is positioned on the last current one. instead of getting 3 frames again, we only get two frames. While the Full_list has 3 selection (Full_List is a list containing the information of the selections made). I think the problem is with the var variable which I can't seem to resolve. in the code, this happens between the selectItem (frame) and removeLabel (frame, var) function. thanks for your time for a solution.
# coding:utf-8
# version 3.x python
import sys
from tkinter import *
from tkinter.ttk import *
from tkinter import messagebox # Librairie des fenêtres d'alerte
# ================= ID python ============================
print("TkVersion", TkVersion)
print("TclVersion", TclVersion)
print("Python version", sys.version_info)
import sys; print('Python %s on %s' % (sys.version, sys.platform))
# ================= Liaison file py =========================
import HV_DB_BackEnd
class Main:
def __init__(self, root):
self.root = root
self.root.title("--------------")
self.root.geometry("700x660+0+0")
self.root.config(bg="cadet blue")
if __name__ == '__main__':
root = Tk()
application = Main(root)
# --- Déclaration Variables - Tableaux
frames = [] # Liste Frames
global Liste_Full
Liste_Full = [] # Liste d'imbrication des L_List (sélection faites depuis Treeview)
# ======================== Frame Treeview ====================
MainFrame = LabelFrame(root, text="[TEST]", relief=FLAT)
MainFrame.place(x=5, y=5, width=1300, height=700)
# ============= Frame hébergeant les sous frame ==============
FrameCalc_1 = Frame(name='labels') #, relief=SOLID, borderwidth=1)
FrameCalc_1.place(x=15, y=300, width=800, height=300)
# ======================== Fonctions ========================
# [Treeview - Heading] - Empêche le redimensionnement des entêtes
def handle_click(event):
if HElist.identify_region(event.x, event.y) == "separator":
if HElist.identify_column(event.x) == '#1':
return "break"
if HElist.identify_column(event.x) == '#2':
return "break"
if HElist.identify_column(event.x) == '#3':
return "break"
if HElist.identify_column(event.x) == '#4':
return "break"
if HElist.identify_column(event.x) == '#5':
return "break"
if HElist.identify_column(event.x) == '#6':
return "break"
# [TreeView widgets] - Affiche Table
def DisplayData():
# Insertion Table BD dans TreeView
a = 0
for i in HV_DB_BackEnd.loadRecord():
HElist.insert('', 'end', text=i[0], values=(i[0], i[1], i[2], i[3], i[4], i[5]))
# print("Index", i[0])
a = a + 1
print(" - Nombre d'enregistrement _ lecture Table", a)
print(" - Nombre d'enregistrement _ lecture Treeview", len(HElist.get_children()))
# Suppression frame(s) générés dynamiquement & MàJ Liste_Full
def removeLabel(frame, var):
print("frames avant suppression", frames)
print("\n", "len(frames) avant", len(frames))
frame.destroy()
Liste_Full.__delitem__(var.get())
ix = frames.index(var) # lit l'indexation de la frame
print("ix - Index de la frame à supprimer ", ix)
frames.pop(ix)
print("frames après suppression", frames)
# Mise à jour de l'indexation var des frame
# for i, v in enumerate(frames[ix:], start=ix):
for i, v in enumerate(frames[0:], start=0):
print("i", i)
v.set(i)
# print("v", i, v.get())
# var.set(v.get())
print("len(frames) après", len(frames))
print("frames restantes", frames)
# Création dynamiquement frame(s) contenant Labels selon la sélection faite depuis TreeView
def selectItem(frame):
var = IntVar()
global frames
frame = Frame(FrameCalc_1, borderwidth=0) # frame à générer dans la frame master FramCalc_1
frame.configure(relief=GROOVE)
frame.grid(row=len(frames) + 1, column=5, pady=1) # Nb de Colonne à générer - pady=intervale entre la prochaine
frame.columnconfigure(0, minsize=135) # Largeur de la Colonne
frame.columnconfigure(1, minsize=30)
frame.columnconfigure(2, minsize=30)
frame.columnconfigure(3, minsize=50)
frame.columnconfigure(4, minsize=30)
frame.columnconfigure(5, minsize=80)
frame.columnconfigure(6, minsize=0)
# === [Listing Table dans Widget Treeview] ===
curItem = HElist.focus()
Liste = HElist.item(curItem)["values"]
# === [Génére automatiquement de nouveaux widgets Labels] ===
var.set(len(frames)) # Compte le nombre de frame
print(var.get())
if var.get() < 5:
print("\n" + "var.get()", var.get())
L_Line = [] # Liste temporaire pour chaque sélection
# -- Génère Label - Affiche le Nb de Frame généré
Label(frame, textvariable=var).grid(row=0, column=0)
# print("frame.winfo_children()[0] - Label compteur", frame.winfo_children()[0]) # .labels.!frame.!label
frames.append(var) # liste des frames générée
# print("frames", frames)
# print("nombre de frames générée-addNewLabel", len(frames))
# -- Génére widget Label - Nom
if Liste[0] != "":
Label(frame, text=Liste[1]).grid(row=0, column=1)
L_Line.append(Liste[1])
# -- Génére widget Label
if Liste[0] != "":
Label(frame, text=Liste[3]).grid(row=0, column=2)
L_Line.append(Liste[3])
# -- Génére widget Label
if Liste[0] != "":
Label(frame, text=Liste[5]).grid(row=0, column=3)
L_Line.append(Liste[5])
# -- Génére widget Entry
if Liste[0] != "":
Input_gr = ""
# takefocus=True autorise la tabulation via la touche TAB
l=Entry(frame, width=4, text="", takefocus=True)
l.grid(row=0, column=4)
# print("frame.winfo_children()[3] ", frame.winfo_children()[3])
Input_gr = frame.winfo_children()[3]
L_Line.append(Liste[0])
# -- Génére Label -
if Liste[0] != "":
lb_pourcentage = ""
Label(frame, text="").grid(row=0, column=5)
lb_pourcentage = frame.winfo_children()[4] # Récupère le nom du label
# print("frame.winfo_children()[4] ", frame.winfo_children()[4])
L_Line.append(Liste[0])
# -- Génére widget Button
# takefocus=False supprime la tabulation via la touche TAB
b = Button(frame, text="Supprimer", width=10, takefocus=False, command=lambda: removeLabel(frame, var))
b.grid(row=0, column=5)
# print("frame.winfo_children()[5] - Button Supprimer", frame.winfo_children()[5]) # .labels.!frame.!button
# print("")
# print("frame.winfo_children()", frame.winfo_children())
Liste_Full.append(L_Line[0:len(L_Line)]) # Imbrique L_Line dans Liste_Full
print("Liste_Full", Liste_Full) # exemple [['test_14', 53, '0.142', 38, 38], ['test_0', 92, '0.138', 9, 9]]
print("frames add", frames)
# ============= Style Police : Treeview_Button_Label ==============
style = Style()
# Treeview
style.configure('.', foreground="black") # Configuration TxT de la Frame contenant Treeview
style.configure('TTreeview', rowheight=15, font=('verdana', 8, ''), foreground='white', background='dim gray')
style.configure('TTreeview.Heading', font=('verdana', 8, ''), foreground="black", cursor='none')
style.layout('TTreeview', [])
# ===== Treeview & Scrollbar Vertical/Horizontal [XY]
scrollbar_y = Scrollbar(MainFrame, orient='vertical') # Ascenseur Vertical
scrollbar_y.place(x=1236, y=24, height=169)
scrollbar_x = Scrollbar(MainFrame, orient='horizontal') # Ascenseur Horizontal
scrollbar_x.place(x=1, y=177, width=1236)
HElist = Treeview(MainFrame, selectmode="browse", columns=(1,2,3,4,5,6), show="headings") #, yscrollcommand=scrollbar_y.set, xscrollcommand=scrollbar_x.set) # style='TTreeview'
# En-tête
HElist.heading('#1', text="ID")
HElist.heading('#2', text="Nom")
HElist.heading('#3', text="C0")
HElist.heading('#4', text="C1")
HElist.heading('#5', text="C2")
HElist.heading('#6', text="C3")
HElist.column('#1', width=0, minwidth=0, stretch=False)
HElist.column('#2', width=160, minwidth=160, stretch=OFF)
HElist.column('#3', width=50, minwidth=50, anchor=CENTER, stretch=OFF)
HElist.column('#4', width=57, minwidth=57, anchor=CENTER, stretch=OFF)
HElist.column('#5', width=120, minwidth=120, stretch=OFF)
HElist.column('#6', width=200, minwidth=200, stretch=OFF)
HElist.place(x=2, y=2, width=1236, height=175)
# Cache colonne(s)
exclusionlist = ['1'] # Colonne [ID] exclue d'affichage
displaycolumns = ['2', '3', '4', '5', '6'] # Colonne [xxx] affichées
for col in HElist["columns"]:
if not "%s" % col in exclusionlist:
pass
HElist["displaycolumns"] = displaycolumns
scrollbar_y.config(command=HElist.yview) # Ascenseur Vertical
scrollbar_x.config(command=HElist.xview) # Ascenseur Horizontal
DisplayData()
# Affiche Entry widget, via souris, la sélection des Datas [Colonnes Treeview]
HElist.bind('<ButtonRelease-1>', selectItem) # Le bouton de la souris a été relâché
# Désactive le redimensionnement des Entêtes Treeview
HElist.bind('<Button-1>', handle_click) # Gauche
HElist.bind('<Button-2>', handle_click) # Molette
HElist.bind('<Button-3>', handle_click) # Droite
root.mainloop()

Related

I import another page in tkinter but it is empty

as you can see when importing this window through the menu, it is empty:
https://i.stack.imgur.com/k9kcu.png
but if I import it directly through main.py, the interface is normal:
https://i.stack.imgur.com/TXHuU.png
I imported other pages and they were correct enter image description here:
https://i.stack.imgur.com/4TBSz.png
main form:
from tkinter import *
import tkinter as tk
#from forms.login.form_login import Login
from PIL import Image, ImageTk
from forms.empresadev.funcioario import PainelFuncionario
from forms.empresadev.setor import PainelSetor
from forms.empresadev.horario import Painelhorario
from forms.gestao import Painel_gestao
class PainelPrincipal:
def __init__(self):
global cur_width, expanded
self.root = tk.Tk()
self.root.title("Your Company")
self.root.geometry('1280x720')
self.min_w = 50 # Minimum width of the frame
self.max_w = 200 # Maximum width of the frame
self.cur_width = self.min_w # Increasing width of the frame
self.expanded = False # Check if it is completely exanded
def importlogin():
self.root.destroy()
def importhorario():
Painelhorario()
def importsetor():
PainelSetor()
def importfunc():
PainelFuncionario()
def importgest():
Painel_gestao()
def expand():
global cur_width, expanded
self.cur_width += 10 # Increase the width by 10
rep = self.root.after(5,expand) # Repeat this func every 5 ms
frame.config(width=self.cur_width) # Change the width to new increase width
if self.cur_width >= self.max_w: # If width is greater than maximum width
expanded = True # Frame is expended
self.root.after_cancel(rep) # Stop repeating the func
fill()
def contract():
global cur_width, expanded
self.cur_width -= 10 # Reduce the width by 10
rep = self.root.after(5,contract) # Call this func every 5 ms
frame.config(width=self.cur_width) # Change the width to new reduced width
if self.cur_width <= self.min_w: # If it is back to normal width
expanded = False # Frame is not expanded
self.root.after_cancel(rep) # Stop repeating the func
fill()
def fill():
if expanded: # If the frame is exanded
# Show a text, and remove the image
home_b.config(text='Inicio',image='',font=(0,21))
set_b.config(text='Setor',image='',font=(0,21))
hour_b.config(text='Horários',image='',font=(0,21))
func_b.config(text='Funcionarios',image='',font=(0,21))
gest_b.config(text='Gestão',image='',font=(0,21))
termses_b.config(text='Terminar Sessão',image='',font=(0,17))
else:
# Bring the image back
home_b.config(image=home,font=(0,21))
set_b.config(image=settings,font=(0,21))
hour_b.config(image=hour,font=(0,21))
func_b.config(image=func,font=(0,21))
gest_b.config(image=gest,font=(0,21))
termses_b.config(image=termses,font=(0,21))
# Define the icons to be shown and resize it
home = ImageTk.PhotoImage(Image.open("./imagens/home.png").resize((40,40),Image.ANTIALIAS))
settings = ImageTk.PhotoImage(Image.open("./imagens/setor.png").resize((40,40),Image.ANTIALIAS))
hour = ImageTk.PhotoImage(Image.open("./imagens/horario.png").resize((40,40),Image.ANTIALIAS))
func = ImageTk.PhotoImage(Image.open("./imagens/funcionario.png").resize((40,40),Image.ANTIALIAS))
gest = ImageTk.PhotoImage(Image.open("./imagens/time.png").resize((45,45),Image.ANTIALIAS))
termses = ImageTk.PhotoImage(Image.open("./imagens/logout.png").resize((40,40),Image.ANTIALIAS))
self.root.update() # For the width to get updated
frame = Frame(self.root,bg='#4fa882',width=50,height=self.root.winfo_height())
frame.grid(row=0,column=0)
# Make the buttons with the icons to be shown
home_b = Button(frame,image=home,bg='#4fa882',relief='flat', overrelief='ridge')
set_b = Button(frame,image=settings,bg='#4fa882',relief='flat', overrelief='ridge',command=importsetor)
hour_b = Button(frame,image=hour,bg='#4fa882',relief='flat', overrelief='ridge',command=importhorario)
func_b = Button(frame,image=func,bg='#4fa882',relief='flat', overrelief='ridge',command=importfunc)
gest_b = Button(frame,image=gest,bg='#4fa882',relief='flat', overrelief='ridge',command=importgest)
termses_b = Button(frame,image=termses,bg='#4fa882',relief='flat', overrelief='ridge',command=importlogin)
# Put them on the frame
home_b.grid(row=0,column=0,pady=10)
set_b.grid(row=1,column=0,pady=30)
hour_b.grid(row=2,column=0,pady=30)
func_b.grid(row=3,column=0,pady=30)
gest_b.grid(row=4,column=0,pady=30)
termses_b.grid(row=5,column=0,pady=30)
# Bind to the frame, if entered or left
frame.bind('<Enter>',lambda e: expand())
frame.bind('<Leave>',lambda e: contract())
# So that it does not depend on the widgets inside the frame
frame.grid_propagate(False)
self.root.mainloop()
management(gestao) form:
from tkinter import *
from tkinter import Tk
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
from tkinter.ttk import Progressbar
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
#from matplotlib.figure import Figure
from tkcalendar import DateEntry
#from datetime import date
from tkinter import messagebox
from forms.empresadev.view import *
#cores
co0 = "#f0f3f5" #Preta
co1 = "#feffff" #Branca
co2 = "#4fa882" #Verde
co3 = "#38576b" #valor
co4 = "#000000" #letra
co5 = "#e06636" #- profit
co6 = "#038cfc" #azul
co7 = "#ef5350" #vermelha
co8 = "#263238" #+ verde
co9 = "#e9edf5" #+ skyblue
colors= ['#5588bb', '#66bbbb', '#99bb55', '#ee9944', '#444466', '#bb5555']
class Painel_gestao():
def __init__(self):
self.janela = Toplevel()
self.janela.title("Gestão")
self.janela.geometry('900x650')
self.janela.configure(background=co9)
self.janela.resizable(width=FALSE, height=FALSE)
self.janela.focus_force()
self.janela.grab_set()
style= ttk.Style(self.janela)
style.theme_use('clam')
#frames para divisão de ecrã
framecima = Frame(self.janela, width=1043, height=50, bg=co1, relief="flat")
framecima.grid(row=0,column=0)
framemeio = Frame(self.janela, width=1043, height=360, bg=co1,pady=20,relief="raised")
framemeio.grid(row=1,column=0, pady=1, padx=0, sticky=NSEW)
framebaixo = Frame(self.janela, width=1043, height=300, bg=co1,relief="raised")
framebaixo.grid(row=2 ,column=0, pady=0, padx=10, sticky=NSEW)
frame_gra_pie = Frame(framemeio, width=580, height=250, bg=co2)
frame_gra_pie.place(x=415, y=5)
# trabalhar com frame cima
#acessar a imagem
self.app_img = Image.open('./imagens/stock.png')
self.app_img = self.app_img.resize((45,45))
self.app_img = ImageTk.PhotoImage(self.app_img)
self.app_logo = Label(framecima, image=self.app_img, text="Orçamento da Empresa", width=900, compound=LEFT, padx=5, relief=RAISED,anchor=NW, font=("Verdana 20 bold"), bg=co1, fg=co4)
self.app_logo.place(x=0,y=0)
#definir tree como global
global tree
#função inserir categoria
def inserir_categoria_b():
nome = e_insira_categoria.get()
lista_inserir = [nome]
if nome=="":
messagebox.showerror('Erro', 'Preencha todos os campos')
else:
inserir_categoria(lista_inserir)
messagebox.showinfo("Sucesso","Os dados foram inseridos com sucesso")
e_insira_categoria.delete(0,'end')
categoria_funcao = mostrar_categoria()
categoria = []
for i in categoria_funcao:
categoria.append(i[1])
#atualizar a lista de categorias
combo_categoria_despesa['values'] = (categoria)
def inserir_receita_b():
nome = 'Receita'
data = e_data_receita.get()
quantia = e_valor_receita.get()
lista_inserir = [nome, data, quantia]
for i in lista_inserir:
if i=='':
messagebox.showerror('Erro', 'Preencha todos os campos')
return
# chamando a função inserir receitas presente na view
inserir_receita(lista_inserir)
messagebox.showinfo('Sucesso', 'Os dados foram inseridos com sucesso')
e_data_receita.delete(0,'end')
e_valor_despesas.delete(0,'end')
# atualizando dados
mostrar_renda()
percentagem()
grafico_pie()
resumo()
grafic_bars()
def apagar():
try:
treev_dados = tree.focus()
treev_dicionario = tree.item(treev_dados)
treev_lista = treev_dicionario['values']
valor = treev_lista[0]
nome = treev_lista[1]
if nome =='Receita':
apagar_receita([valor])
messagebox.showinfo('Sucesso','Os dados foram apagados com sucesso')
# atualizando dados
mostrar_renda()
percentagem()
grafico_pie()
resumo()
grafic_bars()
else:
apagar_gasto([valor])
messagebox.showinfo('Sucesso','Os dados foram apagados com sucesso')
# atualizando dados
mostrar_renda()
percentagem()
grafico_pie()
resumo()
grafic_bars()
except IndexError:
messagebox.showerror('Erro','Seleciona um dos dados na tabela')
#inserir desepesas
def inserir_gasto_b():
nome = combo_categoria_despesa.get()
data = e_data_despesas.get()
quantia = e_valor_despesas.get()
lista_inserir = [nome, data, quantia]
for i in lista_inserir:
if i=='':
messagebox.showerror('Erro', 'Preencha todos os campos')
return
# chamando a função inserir receitas presente na view
inserir_gasto(lista_inserir)
messagebox.showinfo('Sucesso', 'Os dados foram inseridos com sucesso')
combo_categoria_despesa.delete(0,'end')
e_data_despesas.delete(0,'end')
e_valor_despesas.delete(0,'end')
# atualizando dados
mostrar_renda()
percentagem()
grafico_pie()
resumo()
grafic_bars()
def percentagem():
l_nome = Label(framemeio, text="Porcentagem da receita restante", height=1,anchor=NW,font=('Verdana 12'), bg=co1, fg=co4)
l_nome.place(x=7, y=5)
style = ttk.Style()
style.theme_use('default')
style.configure("black.Horizontal.TProgressbar", background='#daed6b')
style.configure("TProgressbar", thickness=25)
bar= Progressbar(framemeio, length=180, style='black.Horizontal.TProgressbar')
bar.place(x=10, y=35)
bar['value'] = percentagem_valor()[0]
valor = percentagem_valor()[0]
l_percentagem = Label(framemeio, text="{:,.2f}".format(valor),anchor=NW,font=('verdana 12'), bg=co1, fg=co4)
l_percentagem.place(x=200, y=35)
#função para gráfico de barra
def grafic_bars():
lista_categoria = ['Renda','Despesas','Saldo']
lista_valores = bar_valores()
# faça figura e atribua objetos de eixo
figura = plt.Figure(figsize=(4, 3.45), dpi=60)
ax = figura.add_subplot(111)
# ax.autoscale(enable=True, axis='both', tight=None)
ax.bar(lista_categoria, lista_valores, color=colors, width=0.9)
# create a list to collect the plt.patches data
c = 0
# set individual bar lables using above list
for i in ax.patches:
# get_x pulls left or right; get_height pushes up or down
ax.text(i.get_x()-.001, i.get_height()+.5,
str("{:,.0f}".format(lista_valores[c])), fontsize=17, fontstyle='italic', verticalalignment='bottom',color='dimgrey')
c += 1
ax.set_xticklabels(lista_categoria,fontsize=16)
ax.patch.set_facecolor('#ffffff')
ax.spines['bottom'].set_color('#CCCCCC')
ax.spines['bottom'].set_linewidth(1)
ax.spines['right'].set_linewidth(0)
ax.spines['top'].set_linewidth(0)
ax.spines['left'].set_color('#CCCCCC')
ax.spines['left'].set_linewidth(1)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.tick_params(bottom=False, left=False)
ax.set_axisbelow(True)
ax.yaxis.grid(False, color='#EEEEEE')
ax.xaxis.grid(False)
canva = FigureCanvasTkAgg(figura, framemeio)
canva.get_tk_widget().place(x=10, y=70)
def resumo():
valor = bar_valores()
l_linha = Label(framemeio, text="", width=215,height=1, anchor=NW, font=('Arial 1'),bg='#545454')
l_linha.place(x=309, y=52)
l_sumario = Label(framemeio, text="Total Renda Mensal".upper(), width=22,height=1, anchor=NW, font=('Verdana 12'),bg=co1,fg='#83a9e6')
l_sumario.place(x=309, y=35)
l_sumario = Label(framemeio, text="€ {:,.2f}".format(valor[0]), width=10,height=1, anchor=NW, font=('arial 17'),bg=co1,fg='#545454')
l_sumario.place(x=309, y=70)
l_linha = Label(framemeio, text="", width=215,height=1, anchor=NW, font=('Arial 1'),bg='#545454')
l_linha.place(x=309, y=132)
l_sumario = Label(framemeio, text="Total Despesas Mensais".upper(), width=22,height=1, anchor=NW, font=('Verdana 12'),bg=co1,fg='#83a9e6')
l_sumario.place(x=309, y=115)
l_sumario = Label(framemeio, text="€ {:,.2f}".format(valor[1]), width=10,height=1, anchor=NW, font=('arial 17'),bg=co1,fg='#545454')
l_sumario.place(x=309, y=150)
l_linha = Label(framemeio, text="", width=215,height=1, anchor=NW, font=('Arial 1'),bg='#545454')
l_linha.place(x=309, y=207)
l_sumario = Label(framemeio, text="Total Saldo".upper(), width=22,height=1, anchor=NW, font=('Verdana 12'),bg=co1,fg='#83a9e6')
l_sumario.place(x=309, y=190)
l_sumario = Label(framemeio, text="€ {:,.2f}".format(valor[2]), width=10,height=1, anchor=NW, font=('arial 17'),bg=co1,fg='#545454')
l_sumario.place(x=309, y=220)
# funcao grafico pie
def grafico_pie():
# faça figura e atribua objetos de eixo
figura = plt.Figure(figsize=(5, 3), dpi=90)
ax = figura.add_subplot(111)
lista_valores = pie_valores()[1]
lista_categorias = pie_valores()[0]
# only "explode" the 2nd slice (i.e. 'Hogs')
explode = []
for i in lista_categorias:
explode.append(0.05)
ax.pie(lista_valores, explode=explode, wedgeprops=dict(width=0.2), autopct='%1.1f%%', colors=colors,shadow=True, startangle=90)
ax.legend(lista_categorias, loc="center right", bbox_to_anchor=(1.55, 0.50))
canva_categoria = FigureCanvasTkAgg(figura, frame_gra_pie)
canva_categoria.get_tk_widget().grid(row=0, column=0)
percentagem()
grafic_bars()
resumo()
grafico_pie()
#criação de frames dentro do frame baixo
frame_renda = Frame(framebaixo, width=300, height=250, bg=co1, relief="flat")
frame_renda.grid(row=0,column=0)
frame_operacoes = Frame(framebaixo, width=300, height=250, bg=co1, relief="flat")
frame_operacoes.grid(row=0,column=1, padx=5)
frame_configuracao = Frame(framebaixo, width=300, height=250, bg=co1, relief="flat")
frame_configuracao.grid(row=0,column=2, padx=5)
# Tabela Renda Mensal----
app_tabela = Label(framemeio, text="Tabela Receitas e Despesas",anchor=NW, font=('Verdana 12 bold'), bg=co1, fg=co4)
app_tabela.place(x=5,y=309)
# funcao para mostrar_renda
def mostrar_renda():
# creating a treeview with dual scrollbars
tabela_head = ['#Id','Categoria','Data','Quantia']
lista_itens = tabela()
global tree
tree = ttk.Treeview(frame_renda, selectmode="extended",columns=tabela_head, show="headings")
# vertical scrollbar
vsb = ttk.Scrollbar(frame_renda, orient="vertical", command=tree.yview)
# horizontal scrollbar
hsb = ttk.Scrollbar(frame_renda, orient="horizontal", command=tree.xview)
tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
tree.grid(column=0, row=0, sticky='nsew')
vsb.grid(column=1, row=0, sticky='ns')
hsb.grid(column=0, row=1, sticky='ew')
hd=["center","center","center", "center"]
h=[30,100,100,100]
n=0
for col in tabela_head:
tree.heading(col, text=col.title(), anchor=CENTER)
# adjust the column's width to the header string
tree.column(col, width=h[n],anchor=hd[n])
n+=1
for item in lista_itens:
tree.insert('', 'end', values=item)
mostrar_renda()
#configurações despesas
l_descricao = Label(frame_operacoes, text="Inserir nova Despesa",height=1,anchor=NW, font=('Verdana 10 bold'), bg=co1,fg=co4)
l_descricao.place(x=10, y=10)
#categoria
l_categoria = Label(frame_operacoes, text="Categoria",height=1,anchor=NW, font=('Ivy 10'), bg=co1,fg=co4)
l_categoria.place(x=10, y=40)
#Get categorias
categoria_funcao= mostrar_categoria()
categoria = []
for i in categoria_funcao:
categoria.append(i[1])
combo_categoria_despesa =ttk.Combobox(frame_operacoes,width=10,font=('Ivy 10'))
combo_categoria_despesa['values'] = (categoria)
combo_categoria_despesa.place(x=110, y=40)
#despesas
l_data_despesas = Label(frame_operacoes, text="Data",height=1,anchor=NW, font=('Ivy 10'), bg=co1,fg=co4)
l_data_despesas.place(x=10, y=70)
e_data_despesas = DateEntry(frame_operacoes, width=12, background='darkblue', foreground='white', borderwidth=2, year=2023)
e_data_despesas.place(x=110, y=70)
l_valor_despesas = Label(frame_operacoes, text="Valor",height=1,anchor=NW, font=('Ivy 10'), bg=co1,fg=co4)
l_valor_despesas.place(x=10, y=100)
e_valor_despesas = Entry(frame_operacoes,width=14, justify='left', relief='solid')
e_valor_despesas.place(x=110,y=100)
#Botão Inserir
img_add_despesa = Image.open('./imagens/plus.png')
img_add_despesa = img_add_despesa.resize((17,17))
img_add_despesa = ImageTk.PhotoImage(img_add_despesa)
botao_inserir_despezas = Button(frame_operacoes,command=inserir_gasto_b, image=img_add_despesa, text="Adicionar".upper(), width=80, compound=LEFT,anchor=NW, font=("Ivy 7 bold"), bg=co1, fg=co2,overrelief=RIDGE)
botao_inserir_despezas.place(x=110,y=130)
#Botão Excluir
img_apagar = Image.open('./imagens/delete.png')
img_apagar = img_apagar.resize((17,17))
img_apagar = ImageTk.PhotoImage(img_apagar)
l_apagar = Label(frame_operacoes, text="Apagar Dados",height=1,anchor=NW, font=('Ivy 10 bold'), bg=co1,fg=co4)
l_apagar.place(x=10, y=190)
botao_apagar = Button(frame_operacoes,command=apagar, image=img_apagar, text="Apagar".upper(), width=80, compound=LEFT,anchor=NW, font=("Ivy 7 bold"), bg=co1, fg=co2,overrelief=RIDGE)
botao_apagar.place(x=110,y=190)
#Configurações receitas
l_info = Label(frame_configuracao, text="Inserir nova Receita",height=1,anchor=NW, font=('Verdana 10 bold'), bg=co1,fg=co4)
l_info.place(x=10, y=10)
#Inserir data receita
l_data_receita = Label(frame_configuracao, text="Data",height=1,anchor=NW, font=('Ivy 10'), bg=co1,fg=co4)
l_data_receita.place(x=10, y=40)
e_data_receita = DateEntry(frame_configuracao, width=12, background='darkblue', foreground='white', borderwidth=2, year=2023)
e_data_receita.place(x=110, y=40)
#valor receita
l_valor_receita = Label(frame_configuracao, text="Valor",height=1,anchor=NW, font=('Ivy 10'), bg=co1,fg=co4)
l_valor_receita.place(x=10, y=70)
e_valor_receita = Entry(frame_configuracao,width=14, justify='left', relief='solid')
e_valor_receita.place(x=110,y=70)
botao_inserir_receita = Button(frame_configuracao,command=inserir_receita_b, image=img_add_despesa, text="Adicionar".upper(), width=80, compound=LEFT,anchor=NW, font=("Ivy 7 bold"), bg=co1, fg=co2,overrelief=RIDGE)
botao_inserir_receita.place(x=110,y=130)
l_insira_categoria = Label(frame_configuracao, text="Categoria",height=1,anchor=NW, font=('Verdana 10 bold'), bg=co1,fg=co4)
l_insira_categoria.place(x=10, y=170)
e_insira_categoria = Entry(frame_configuracao,width=14, justify='left', relief='solid')
e_insira_categoria.place(x=110,y=170)
#Botão Inserir2
img_add_categoria = Image.open('./imagens/plus2.png')
img_add_categoria = img_add_categoria.resize((17,17))
img_add_categoria = ImageTk.PhotoImage(img_add_categoria)
botao_inserir_categoria = Button(frame_configuracao,command=inserir_categoria_b, image=img_add_categoria, text="Adicionar".upper(), width=80, compound=LEFT,anchor=NW, font=("Ivy 7 bold"), bg=co1, fg=('blue'),overrelief=RIDGE)
botao_inserir_categoria.place(x=110,y=195)
self.janela.mainloop()

Click on a button and advance to the limit of the window in tinker

i am trying to learn python from a book. I'm trying to do an exercise with tinker. Click on a button and advance to the limit of the window. Then always by clicking on the same button to advance the circle to the other side of the window. Thanks for your help.
from tkinter import *
def avance(n, g):
global x, y, step
# nouvelles coordonnées :
x[n] = x[n] + g # deplacement de l'axe des x
# déplacement du dessin dans le canevas :
can.coords(bille[n], x[n]-10, y[n]-10, x[n]+10, y[n]+10)
# affichage pour info du x:
Info.configure(text="Coordonnée x = " + str(x[n]))
i = 0
if x[n] >= 50:
while i <= 400:
step = +20
i = i+5
if x[n] >= 400:
step = -20
i = i-5
return step
def go():
avance(0, step)
bille = [0] # liste servant à mémoriser les références du cercle
x = [50] # X de départ
y = [100] # y de départ
step = 0 # "pas" de déplacement initial
# Construction de la fenêtre :
fen = Tk()
fen.title("avance quand on clique jusqu'à la limite de la fenêtre et revient")
Info = Label(fen) # pour afficher l'info du x
Info.grid(row=3, column=0)
# Canvas :
can = Canvas(fen, bg="white", width=400, height=200)
can.grid(row=2, column=0, columnspan=2)
bille[0] = can.create_oval(x[0]-10, y[0]-10, x[0]+10, y[0]+10,
fill="blue")
# bouton avance :
f = Frame(fen)
f.grid(row=4, column=0, sticky=W, padx=10)
Button(f, text="Go", fg='blue', command=go).pack(side=LEFT)
fen.mainloop()
the problem is that when the ball reaches the limit (first while loop) when it starts the second loop, it returns to the conditions of the first.
sorry for my English
thank for help
I solved my problem.
here is my solution
from tkinter import *
def avance(n, g):
global x, y, step
# nouvelles coordonnées :
x[n] = x[n] + g # deplacement de l'axe des x
# déplacement du dessin dans le canevas :
can.coords(bille[n], x[n]-10, y[n]-10, x[n]+10, y[n]+10)
# affichage pour info du x:
Info.configure(text="Coordonnée x = " + str(x[n]))
i = 0
if 5 >= x[n] < 400: # 5 superieur ou egale à x et x inferieur à 400 , execute la ligne suivante
step=+20
return step
if 5 <= x[n] >= 400: # 5 inferieur ou egale à x et x superieur ou egale à 400 , execute la ligne suivante
step = -20
return step
# x egale 50 execute le premier if..
def go():
avance(0, step)
step = 0 # variable pour le pas d'avancement
bille = [0] # liste servant à mémoriser les références du cercle
x = [5] # X de départ
y = [100] # y de départ
# "pas" de déplacement initial
# Construction de la fenêtre :
fen = Tk()
fen.title("avance quand on clique jusqu'à la limite de la fenêtre et revient")
Info = Label(fen) # pour afficher l'info du x
Info.grid(row=3, column=0)
# Canvas :
can = Canvas(fen, bg="white", width=400, height=200)
can.grid(row=2, column=0, columnspan=2)
bille[0] = can.create_oval(x[0]-10, y[0]-10, x[0]+10, y[0]+10,
fill="blue")
# bouton avance :
f = Frame(fen)
f.grid(row=4, column=0, sticky=W, padx=10)
Button(f, text="Go", fg='blue', command=go).pack(side=LEFT)
fen.mainloop()

Problems when positioning buttons with tkinter

I'm having trouble creating buttons in tkinter, I've tried doing it in different ways, but I haven't reached the solution.
It turns out that one of the requirements that they have made me when making this calculator is to create three text boxes and eleven buttons, so when I create the positioning of the boxes and I want to place the buttons they do nothing, if I try to tell them to position in column 3, row 4 is not positioned.
Image of the code output
This is the code, if you see something wrong that I have not been able to see and that is the cause of such an error, I would appreciate it
from tkinter import *
#instancia de calculadora
calculadora = Tk()
#Nombre de la ventana grafica
calculadora.title("Practica calculadora con tkinter")
#tamano de la ventana
calculadora.geometry("600x750")
#color personalizado de la ventana
calculadora.configure(bg="black")
firtDisplay = Entry(calculadora, state="readonly", width=25).place(x=0, y=5)
secondDisplay = Entry(calculadora, state="readonly", width=25).place(x=300, y=5)
thirdDisplay = Entry(calculadora, state="readonly", width=25).place(x=149, y=40)
#Botones
Button(calculadora, text="7", width=15).grid(row=5, column=3)
Button(calculadora, text="8", width=15)
Button(calculadora, text="9", width=15)
calculadora.mainloop()
Please help would be very good, thank you ...
I think you must first of all use only one type of geometry management, and then keep it simplest, I've made some changes to show how to use grid manager with some loop.
from tkinter import *
#instancia de calculadora
calculadora = Tk()
#Nombre de la ventana grafica
calculadora.title("Practica calculadora con tkinter")
#tamano de la ventana
#calculadora.geometry("600x750")
#color personalizado de la ventana
#calculadora.configure(bg="black")
r = 0
c = 0
for i in range(0,4):
if i < 3:
Entry(calculadora, state="readonly", width=15).grid(row=r, column=c)
else:
Checkbutton(calculadora, width=15, text="/").grid(row=r, column=c)
c +=1
array = (("7","8","9","x"),("4","5","6","-"),("1","2","3","+"))
r = 1
c = 0
for items in array:
for i in items:
index = items.index(i)
if index < 3:
Button(calculadora, text=i, width=15).grid(row=r, column=c)
else:
Checkbutton(calculadora, width=15, text=i).grid(row=r, column=c)
c +=1
r +=1
c = 0
calculadora.mainloop()
You souldn't mix .pack(), .grid(), and .place() in the same master window.

Float is required (in Tkinter)

I have a problem that i still cant solve, specifically involving tkinter.
Eventhough some parts of the code are written in spanish I hope its not a problem.
When trying to calculate the hypotenuse of a triangle with Vel_in_y as the opposing side.
import tkinter
import math
window= tkinter.Tk()
frame = tkinter.Frame(window)
frame.pack()
Velocidad_in =tkinter.IntVar()
Angulo_desp = tkinter.IntVar()
Altura_max = tkinter.IntVar()
Alcan = tkinter.IntVar()
Temp = tkinter.IntVar()
Vel_in_y= tkinter.IntVar()
Vel_in_x= tkinter.IntVar()
var = [Velocidad_in,Angulo_desp ,Altura_max,Alcan,Temp,Vel_in_y,Vel_in_x]
opciones_de_Vel = ['Velocidad Inicial en X','Velocidad Inicial en Y','Modulo de Velocidad']
def Velocidad_Inicial(root):
for (tipo,var) in ((' La Velocidad Inicial en X',Vel_in_x),(' La Velocidad Inicial en Y',Vel_in_y),(' El Modulo de Velocidad',Velocidad_in)):
label = tkinter.Label(frame,text= 'Inserte '+ tipo)
label.pack()
entry= tkinter.Entry(frame,textvariable = var)
entry.pack()
def Angulo_Despegue(root):
label = tkinter.Label(frame,text='Inserte el Angulo de despegue')
label.pack()
entry= tkinter.Entry(frame,textvariable = Angulo_desp)
entry.pack()
def Altura_Maxima(root):
label = tkinter.Label(frame,text='Inserte la Altura Maxima')
label.pack()
entry= tkinter.Entry(frame,textvariable = Altura_max)
entry.pack()
def Alcance(root):
label = tkinter.Label(frame,text='Inserte el Alcance')
label.pack()
entry= tkinter.Entry(frame,textvariable = Alcan)
entry.pack()
def Tiempo(root):
label = tkinter.Label(frame,text='Inserte el Tiempo')
label.pack()
entry= tkinter.Entry(frame,textvariable = Temp)
entry.pack()
def calcular_modulo(root):
modulo = Vel_in_y* math.sin(Angulo_desp)
label = tkinter.Label(frame,textvariable=modulo)
label.pack()
if modulo == 0:
modulo = math.sqrt(Vel_in_x**2+ Vel_in_y**2)
label = tkinter.Label(frame,textvariable=modulo)
label.pack()
button = tkinter.Button(frame,text='respuesta' ,command = lambda: calcular_modulo(window))
button.pack()
menubar = tkinter.Menu(window)
option_menu =tkinter.Menu(menubar)
option_menu.add_command(label= 'Velocidad Inicial',command=lambda:Velocidad_Inicial(window))
option_menu.add_command(label= 'Angulo de Despegue',command=lambda:Angulo_Despegue(window))
option_menu.add_command(label= 'Altura Maxima',command=lambda:Altura_Maxima(window))
option_menu.add_command(label= 'Alcance',command=lambda:Alcance(window))
option_menu.add_command(label= 'Tiempo', command=lambda:Tiempo(window))
menubar.add_cascade(label= 'Tipo de Variable',menu=option_menu)
window.config(menu=menubar)
window.mainloop()
If you spot an error,Ill apreciate all feedback!
BTW when I run this code I get an error saying :
TypeError: a float is required
modulo = Vel_in_y* math.sin(Angulo_desp.get())
math.sin has no idea what to do with an IntVar ... you must get the value
the same applies everywhere else you are trying to access the value of the variables
I don't understand why you use IntVal instead int .
You need to convert IntVal type to int type by use the get function .
Here is your code , it was fixed :
def calcular_modulo(root):
modulo = Vel_in_y.get()* math.sin(Angulo_desp.get())
label = tkinter.Label(frame,textvariable=modulo)
label.pack()
if modulo == 0:
modulo = math.sqrt(Vel_in_x.get()**2+ Vel_in_y.get()**2)
label = tkinter.Label(frame,textvariable=modulo)
label.pack()

loading screen or change cursor in python Tkinter

I am using Tkinter to create my UI on python.
Currently, the .__init__() and .initialize() are like this:
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid()
self.entryVariable = Tkinter.StringVar()
self.entry = Tkinter.Entry(self,textvariable=self.entryVariable)#Entry é um nome de Textfield da tela
self.entry.grid(column=0,row=0,sticky='EW')#EW é pra ele grudar nas edges
self.entry.bind("<Return>", self.OnPressEnter)#dispara onPressEnter quando enter é pressionado no ttext field
self.entryVariable.set(u"Entre com o nome do amigo que você quer convidar pra sair")
button = Tkinter.Button(self,text=u"Ver compatibilidade!",
command=self.OnButtonClick)#botao clicavel dispara onButtonClick
button.grid(column=1,row=0)
self.labelVariable = Tkinter.StringVar()
#label = Tkinter.Label(self,textvariable=self.labelVariable, # label que usa variável labelVariable como texto
#anchor="w",fg="white",bg="black", height=35, width=55)#NOVO WIDTH E HEIGHT FIXO
#PESQUISAR COMO SE ADD SCROLLBAR PRA LABEL, SE TEM COMO OU ADD LABEL EM WINDOW E AIH BOTAR SCROLLBAR
self.texto = Tkinter.Text(self, fg="white",bg="black", height=35, width=55)
self.texto.grid(column=0,row=1,columnspan=2,sticky='EW')
# create a Scrollbar and associate it with txt
scrollb = Tkinter.Scrollbar(self, command=self.texto.yview)
scrollb.grid(row=1, column=1, sticky='nsew')
self.texto['yscrollcommand'] = scrollb.set
#label.grid(column=0,row=1,columnspan=2,sticky='EW')
self.labelVariable.set(u"Hello !")
self.grid_columnconfigure(0,weight=1)#estica a coluna 1 mesmo com resize da janela
self.resizable(True,True)#soh ppode resize horizontalmente! vertical nao pode
self.update()
self.geometry(self.geometry())
self.entry.focus_set()#textfield foca
self.entry.selection_range(0, Tkinter.END)
On this GUI, I have a button, and on this button, I do this:
def OnButtonClick(self):
#self.labelVariable.set( self.labelVariable.get() + "\n" + self.entryVariable.get()+" (You clicked the button)" ) #muda o texto da labelVariable com o valor de entryVariable
#self.texto.insert(Tkinter.END, self.entryVariable.get() + "\n")
from AcharCompatibilidadeEntreAmigosTudoJunto import AcharCompatibilidadeEntreAmigosTudoJunto
achaCompatibilidade = AcharCompatibilidadeEntreAmigosTudoJunto(self.access_token, self)
achaCompatibilidade.calcularCompatibilidadeEntreEsseAmigoETodosOsMeusAmigos(self.entryVariable.get())
self.entry.focus_set()#seleciona o texto todo assim que o usuário aperta botão ou enter
self.entry.selection_range(0, Tkinter.END)
The problem is that I want to change the cursor of my mouse to a loading cursor when the user clicks on the button and it will have to change back when the .onButtonClick() function ends. How do i do that?
Have the button pressed call a method which sets the cursor into whatever you want it to, and then in the same method start a new thread of the actual method you were trying to call. Then at the end of this method change the cursor back.
This link: http://effbot.org/zone/tkinter-busy.htm should help you with changing of the cursor, and a quick google search or search on this website should give you all the information you need for threading. The module you are looking for is called 'threading' by the way.

Categories