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()
I have an error in my program: "Taula_G3110 ()
NameError: name 'Taula_G3110' is not defined"
My question is:
I want to call a function that is inside an IF loop.This function is in another file. I have tried everything with imports:
"from Kleben_Tabelle import Taula_G3110, Taula_G3111.
import Kleben_Tabelle ", but there is no way.
Does anyone have an idea what I'm doing wrong?
Code:
from tkinter import *
from PIL import Image, ImageTk
from tkinter import ttk
from tkinter import messagebox
#from Kleben_Tabelle import *
import serial
import time
import PIL.Image
import Kleben_Tabelle
root = Tk()
root.geometry("1000x600")
# root.resizable (False,False)
root.title("Combobox")
arduino = serial.Serial("COM7", 9600)
time.sleep(0.1) # reducir el uso de la CPU.Prueba con diferentes valores (0.01 a 0.1)
def cambiar():
mes = combo.get()
if mes == "G3110":
label_resultat.configure(text=txt)
Taula_G3110()
if mes == "G3111":
label_resultat.configure(text=txt2)
Taula_G3111()
if mes == "G3112":
messagebox.showinfo("Mes", "Marzo")
def apagarLED():
arduino.write(b'4')
time.sleep(1)
def cerrarInterfaz():
# cerrar comunicación Serial
global raiz
arduino.close()
# cerrar ventana
root.destroy()
image = Image.open ('Edifici_Knauer_blau.png')
photo_image = ImageTk.PhotoImage(image)
label = Label(root, image=photo_image)
label.pack()
frame_resultat = Frame(root, width=400, height=100, relief="flat", highlightbackground="blue", highlightthickness=1)
frame_resultat.place(x=250, y=200)
label_resultat = Label(root, text="", bg="yellow", borderwidth=0, relief="groove", width=20, height=2, justify='left',
highlightbackground="blue", highlightthickness=1)
label_resultat.place(x=80, y=200)
etiqueta = Label(root, text="Zelle: Kleben")
etiqueta.place(x=100, y=40)
combo = ttk.Combobox(root, state="readonly")
combo.place(x=100, y=70)
combo["values"] = ("G3110", "G3111", "G3112", "1")
combo.current(0)
boton = Button(root, text="Cambiar mes", command=cambiar)
boton.place(x=100, y=100)
# boton de apagado del LED
btnApagar = ttk.Button(root, text="Reset", command=apagarLED)
# btnApagar = ttk.Button(raiz,text ="Reset",command = clearTextInput)
btnApagar.place(x=420, y=450)
# boton de Cerrar interfaz
btnCerrar = ttk.Button(root, text="Cerrar", command=cerrarInterfaz)
btnCerrar.place(x=420, y=480)
txt = ("G3110 Frontabdeckung")
txt2 = ("G3111 Frontabdeckung")
root.mainloop()
and this ist my other File with this Module-Function:(File: Kleben_Tabelle.py)
def Taula_G3110():
arduino.write(bytes(b'T'))
arbol = ttk.Treeview(frame_resultat,columns=("Bauteile","Regal","Lager"))
arbol.column ('#0',width=100)
arbol.column ('Bauteile',width=100)
arbol.column ('Regal',width=80)
arbol.column ('Lager',width=80)
arbol.insert("",END,text="G3110",values=("P6400","K2.0001.01","Regal 2"))
arbol.insert("",END,text="G3110",values=("P6406XA","K1.0004.01"))
arbol.insert("",END,text="G3110",values=("P6403XA","K1.0003.01"))
arbol.heading("#0",text="Model")
arbol.heading("Bauteile",text="Bauteile")
arbol.heading("Regal",text="Regal")
arbol.place(x=100,y=70)
arbol.pack()
In order to call a function in a module that you've imported, you need to reference the module and function like so:
import Kleben_Tabelle
...
def cambiar():
mes = combo.get()
if mes == "G3110":
label_resultat.configure(text=txt)
Kleben_Tabelle.Taula_G3110()
I have in my program two spinboxes, created with tkinter. I want the variables chosen by the user to be added to a list, so I can use those values later in the program. The problem I'm currently having is that the values are stored just once in the list, and I don't manage to update them, despite all of the things I tried. To be clear, I just want two values in the list, so when the user select another number, it will replace the proper value stored in the list.
Here is the code I wrote :
from tkinter import *
windowTk = Tk()
pwMain = PanedWindow(windowTk, orient=VERTICAL)
pwTop = PanedWindow(pwMain, orient=HORIZONTAL)
def configTables() :
sLine = Spinbox(pwTop, from_=0, to=15)
pwTop.add( Label(pwTop, text = "Combien y a-t-il de lignes de table ?") )
pwTop.add( sLine )
sColumn = Spinbox(pwTop, from_=0, to=15)
pwTop.add( Label(pwTop, text = "Combien y a-t-il de colonnes de tables ?") )
pwTop.add( sColumn )
pwTop.pack()
pwMain.pack()
global coordTables
coordTables = []
coordTables.append( int(sLine.get()) )
coordTables.append( int(sColumn.get()) )
return coordTables
print( configTables() )
windowTk.mainloop()
I hope my request is understandable, so you can help me.
Thank you
LoneRetrievr
UPDATE : I tried the following code, and it works, but nothing appears in the window (tkinter's window remains white).
from tkinter import *
windowTk = Tk()
pwMain = PanedWindow(windowTk, orient=VERTICAL)
pwTop = PanedWindow(pwMain, orient=HORIZONTAL)
lines = IntVar(windowTk, value=0)
columns = IntVar(windowTk, value=0)
def configTables() :
sLine = Spinbox(pwTop, from_=0, to=15, textvariable=lines)
pwTop.add( Label(pwTop, text = "Combien y a-t-il de lignes de tables ?") )
pwTop.add( sLine )
sColumn = Spinbox(pwTop, from_=0, to=15, textvariable=columns)
pwTop.add( Label(pwTop, text = "Combien y a-t-il de colonnes de tables ?") )
pwTop.add( sColumn )
pwTop.pack()
pwMain.pack()
numberLines = lines.get()
numberColumns = columns.get()
print( numberLines, numberColumns )
windowTk.mainloop()
I know it will print just once the values and that's what I want it to do.
Can you help me ? I think it's very simple, but I don't find where's the problem.
You can use IntVar to connect the spin boxes to Python variables. I have extended your program with an example. It adds a button to print the current value of the spin boxes:
from tkinter import *
windowTk = Tk()
pwMain = PanedWindow(windowTk, orient=VERTICAL)
pwTop = PanedWindow(pwMain, orient=HORIZONTAL)
lignes = IntVar(windowTk, value=0)
colonnes = IntVar(windowTk, value=0)
def print_vars():
print(lignes.get(), colonnes.get())
def configTables() :
sLine = Spinbox(pwTop, from_=0, to=15, textvariable=lignes)
pwTop.add( Label(pwTop, text = "Combien y a-t-il de lignes de table ?") )
pwTop.add( sLine )
sColumn = Spinbox(pwTop, from_=0, to=15, textvariable=colonnes)
pwTop.add( Label(pwTop, text = "Combien y a-t-il de colonnes de tables ?") )
pwTop.add( sColumn )
pwTop.pack()
b = Button(pwMain, text='print', command=print_vars)
b.pack(side=BOTTOM)
pwMain.pack()
global coordTables
coordTables = []
coordTables.append( int(sLine.get()) )
coordTables.append( int(sColumn.get()) )
return coordTables
print( configTables() )
windowTk.mainloop()
Note, I have not removed things which are no longer necessary, like coordTables variable and the return statement.
this is what you would want to do, I believe.
I suggest you an object oriented approach.
Tkinter has IntVar() and other variables very powerfull.
import tkinter as tk
class App(tk.Frame):
def __init__(self,):
super().__init__()
self.master.title("Hello World")
self.lines = tk.IntVar()
self.columns = tk.IntVar()
self.coordTables = []
self.init_ui()
def init_ui(self):
self.pack(fill=tk.BOTH, expand=1,)
f = tk.Frame()
tk.Label(f, text = "Combien y a-t-il de lignes de tables ?").pack()
tk.Spinbox(f, from_=0, to=15, textvariable= self.lines).pack()
tk.Label(f, text = "Combien y a-t-il de colonnes de tables ?").pack()
tk.Spinbox(f, from_=0, to=15, textvariable= self.columns).pack()
w = tk.Frame()
tk.Button(w, text="Print", command=self.on_callback).pack()
tk.Button(w, text="Reset", command=self.on_reset).pack()
tk.Button(w, text="Close", command=self.on_close).pack()
f.pack(side=tk.LEFT, fill=tk.BOTH, expand=0)
w.pack(side=tk.RIGHT, fill=tk.BOTH, expand=0)
def on_callback(self,):
args = (self.lines.get(),self.columns.get())
self.coordTables.append(args)
print ("Numers of coords: {0}".format(len(self.coordTables)))
for e,i in self.coordTables:
print(e,i)
def on_reset(self):
self.lines.set(0)
self.columns.set(0)
self.coordTables = []
def on_close(self):
self.master.destroy()
if name == 'main':
app = App()
app.mainloop()
I'm developing a GUI where the idea is to add some values to a treeview (as a billing system) and then get the result or sum of all items' prices.
The button "Agregar" (Add in English) get the Entries' data and add them to the treevew; one of them if the amount of money to pay.
Now what I want, and haven't been able to get, is the sum of the values given in the treeview to be shown in the field or entry which is below the treeview when "Generar" (Generate in English) button is pressed.
Next, the code I got:
#!/usr/bin/python
#-*- coding:utf-8 -*-
from Tkinter import*
from ttk import Combobox, Treeview
from tkMessageBox import*
import MySQLdb
from controller import *
import math
class Gastos(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
#INSTANCIAS
global cc, nombre, pago, ref, cod, desc, valor
#INSTANCIAS DE LOS WIDGETS
global e1, e2, e3, e4, e5, tree, l8
cc = IntVar()
nombre = StringVar()
pago = StringVar()
ref = StringVar()
cod = StringVar()
desc = StringVar()
valor = DoubleVar()
tbancos = ['Bancolombia', "Banco Bogotá", "Banco Agrario", "Banco Occidente"]
lupa = PhotoImage(file='img/lupa.png')
tbanktype = ['Corriente','Ahorro']
fpago = ['Efectivo','Transferencia']
resultado = DoubleVar()
#BUSQUEDA = ["Nombre","CC/Nit"]
busqueda = StringVar()
busqueda.trace("w", lambda name, index, mode: buscar())
dato = StringVar()
#WIDGETS
#========================= HEADER ==============================
self.titleL = Label(self, text="GASTOS", font="bold")
self.titleL.pack(pady=20, side=TOP)
#========================== WRAPPER ============================
self.wrapper = Frame (self)
self.wrapper.pack(side=LEFT, fill=Y)
#Esto centro el wrapper
#self.wrapper.pack(side=LEFT, fill=BOTH, expand=True)
#======================== BENEFICIARIO =======================
self.lf1 = LabelFrame(self.wrapper, text="Beneficiario")
self.lf1.pack(fill=X, ipady=5)
self.f0 = Frame(self.lf1)
self.f0.pack(pady=5, fill=X)#-----------------------------------
l1 = Label(self.f0, text='CC/Nit:')
l1.pack(side=LEFT)
e1 = Entry(self.f0, textvariable=cc)
e1.pack(side=LEFT)
b0 = Button(self.f0, text='Buscar:', image=lupa, command=buscarB)
b0.pack(side=LEFT)
l2 = Label(self.f0, text='Nombre:')
l2.pack(side=LEFT)
e2 = Entry(self.f0, textvariable=nombre)
e2.pack(side=LEFT, fill=X, expand=1)
self.f1 = Frame(self.lf1)
self.f1.pack(pady=5, fill=X)#-----------------------------------
l3 = Label(self.f1, text='Forma de Pago:')
l3.pack(side=LEFT)
Cbx = Combobox(self.f1, textvariable=pago, values=fpago, width=15)
Cbx.set('Efectivo')
Cbx.pack(side=LEFT)
l4 = Label(self.f1, text='Ref. Bancaria:')
l4.pack(side=LEFT)
e3 = Entry(self.f1, textvariable=ref)
e3.pack(side=LEFT, fill=X, expand=1)
b1 = Button(self.f1, text='Buscar:', image=lupa)
b1.image=lupa
b1.pack(side=LEFT)
#======================== CONCEPTO ========================
self.lf2 = LabelFrame(self.wrapper, text="Concepto")
self.lf2.pack(fill=X, ipady=5)
self.f2 = Frame(self.lf2)
self.f2.pack(pady=5, fill=X)#-------------------------------
l5 = Label(self.f2, text='Código:')
l5.pack(side=LEFT)
e4 = Entry(self.f2, textvariable=cod)
e4.pack(side=LEFT)
b2 = Button(self.f2, text='Buscar:', image=lupa, command=buscarC)
b2.pack(side=LEFT)
self.f3 = Frame(self.lf2)
self.f3.pack(pady=5, fill=X)#-------------------------------
l6 = Label(self.f3, text='Descripción:')
l6.pack(side=LEFT)
e5 = Entry(self.f3, textvariable=desc, state=DISABLED)
e5.pack(side=LEFT, fill=X, expand=1)
l7 = Label(self.f3, text='Valor:')
l7.pack(side=LEFT)
e6 = Entry(self.f3, width=15, textvariable=valor)
e6.pack(side=LEFT)
b3 = Button(self.f3, text='Agregar:', command=agregar)
b3.pack(side=LEFT)
#-------------------------- TREEVIEW ---------------------------
self.f4 = Frame(self.wrapper)
self.f4.pack(pady=5,fill=X)
tree = Treeview(self.f4, height=4, show="headings", columns=('col1','col2','col3'))
tree.pack(side=LEFT, fill=X, expand=1)
tree.column('col1', width=20, anchor='center')
tree.column('col2', width=200, anchor='center')
tree.column('col3', width=10, anchor='center')
tree.heading('col1', text='Código')
tree.heading('col2', text='Concepto')
tree.heading('col3', text='Valor')
scroll = Scrollbar(self.f4,orient=VERTICAL,command=tree.yview)
tree.configure(yscrollcommand=scroll.set)
#--------------------------------------------------------------
self.f5 = Frame(self.wrapper)
self.f5.pack(pady=5,fill=X)#-------------------
#RESULT MUST BE SHOWN HERE
l8 = Label(self.f5, text=resultado, fg="red", bg="white", anchor='e', font="bold, 22", relief= SUNKEN)
l8.pack(fill=X, side=RIGHT, expand=1)
#l8.set("link")
self.fBtn = Frame(self.wrapper)
self.fBtn.pack()#-------------------------------
clean = Button(self.fBtn, text='Cancelar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=limpiar)
clean.pack(side=RIGHT)
update = Button(self.fBtn, text='Actualizar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', state=DISABLED)
update.pack(side=RIGHT)
add = Button(self.fBtn, text='Generar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=generar)
add.pack(side=RIGHT)
#========================= ASIDE ===========================
self.aside = Frame(self)
self.aside.pack(side=TOP, fill=BOTH)
self.wrap1 = Frame(self.aside)
self.wrap1.pack()
self.viewer = Label(self.wrap1, text="LISTA DE GASTOS")
self.viewer.pack()
scroll = Scrollbar(self.wrap1, orient=VERTICAL)
scroll.pack(side=RIGHT, fill=Y)
lb = Listbox(self.wrap1, yscrollcommand=scroll.set, height=20, width=30)
scroll.config (command=lb.yview)
lb.pack(fill=BOTH)
lb.bind("<Double-Button-1>", callback)
self.wrap2 = Frame(self.aside)
self.wrap2.pack()
load = Button(self.wrap2, text='Cargar lista', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cargar_lista)
load.pack(fill=X)
delete = Button(self.wrap2, text='Borrar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=borrar)
delete.pack(fill=X)
edit = Button(self.wrap2, text='Modificar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=modificar)
edit.pack(fill=X)
buscador = Label(self.wrap2, text="Buscar por Número:")
buscador.pack()
E = Entry(self.wrap2, textvariable=busqueda, width=24)
E.pack()
E.bind("<KeyRelease>", caps)
def cargar_lista():
try:
connect.commit()
display = "SELECT g_num FROM detalles order by g_num;"
cursor.execute(display)
registros = cursor.fetchall()
lb.delete(0, END)
for item in registros:
#print item
num = item[0]
lb.insert(END, num)
except:
showerror("Mensaje", "Ha ocurrido un error")
# NUEVO / CANCELAR
def limpiar():
tree.delete(*tree.get_children())
pass
def agregar():
v1 = cc.get()
v2 = None
v3 = cod.get()
v4 = desc.get()
v5 = valor.get()
tree.insert('', 0, values=(v3,v4,v5))
#FUNCTION THAT GIVE THE VALUES
def generar():
children = tree.get_children()#OBTIENE LOS iid DE LOS ITEMS
for child in children:
i = tree.item(child, 'values')[2]#OBTIENE LOS VALORES DE LOS ITEMS
print i
def borrar():
pass
def bloquear():
pass
def callback(event):
llenar_campos()
def llenar_campos():
pass
def habilitar():
pass
def modificar():
pass
def actualizar():
pass
def buscar():
pass
def buscarB():
connect.commit()
try:
v = cc.get()
sql = "SELECT b_nombre from beneficiarios WHERE b_cc='%d';" % (v)
cursor.execute(sql)
query = cursor.fetchone()
for n in query:
nombre.set(n)
except TypeError, e:
showerror("Error", e)
except MySQLdb.IntegrityError, e:
showerror("Error", e)
def buscarC():
connect.commit()
try:
v = cod.get()
sql = "SELECT cg_nombre from concepto_gastos WHERE cg_cod='%s';" % (v)
cursor.execute(sql)
query = cursor.fetchone()
for n in query:
desc.set(n)
except TypeError, e:
showerror("Error", e)
except MySQLdb.IntegrityError, e:
showerror("Error", e)
except:
showerror ("Mensaje", "No se encuentra!")
# CONVIERTE LA ENTRADA DE LOS ENTRIES EN MAYÚSCULA
def caps(event):
pass
The code is not finished, that's why it has so much info. But next function is what give me the values I need to be sum:
def generar():
children = tree.get_children()#OBTIENE LOS iid DE LOS ITEMS
for child in children:
i = tree.item(child, 'values')[2]#OBTIENE LOS VALORES DE LOS ITEMS
print i
By the way, this file is called by another (home.py) to interact with it.
If anyone could give me a hand this problem, you'll save a life. Thanks for your time, look on this, and anything you could answer. Sorry for my English if it is not good.
You have to convert string to float and then you can add to variable ie. total
def generar():
total = 0.0
for child in tree.get_children():
total += float(tree.item(child, 'values')[2])
print total
But you could add value even in agregar to get total with using button
# create global variables
total = 0.0
# or
total_var = DoubleVar()
def agregar():
# inform function to use external/global variable when you use `+=`
global total
v1 = cc.get()
v2 = None
v3 = cod.get()
v4 = desc.get()
v5 = valor.get()
total += v5
# or
total_var.set(total_var.get() + v5)
tree.insert('', 0, values=(v3,v4,v5))
Full working example
import Tkinter as tk
import ttk
# --- functions ---
def agregar(v3, v4, v5):
tree.insert('', 0, values=(v3,v4,v5))
def generar():
total = 0.0
for child in tree.get_children():
total += float(tree.item(child, 'values')[2])
print total
result['text'] = 'Total: {}'.format(total)
# --- main ---
root = tk.Tk()
tree = ttk.Treeview(root, height=4, show="headings", columns=('col1','col2','col3'))
tree.pack()
tree.heading('col1', text='Código')
tree.heading('col2', text='Concepto')
tree.heading('col3', text='Valor')
add = tk.Button(root, text='Generar', command=generar)
add.pack()
result = tk.Label(root, text='Total: 0')
result.pack()
agregar("1", "AAA", 1.11)
agregar("2", "BBB", 2.22)
agregar("3", "CCC", 3.33)
root.mainloop()
The reason you are getting PY_VAR240 is because your code is trying to display an object instead of a value.
There is already an answer here that hints at the issue as well: Python Tkinter Treeview - Iterating 'get_children' output
Also here is how I get the values from a row:
rowItem = treeSomeTree.item(itemID)
itemDictionary = rowItem['values']
someVariable = itemDictionary[0]
Note the item id variable represents row item identifier which may or may not be a number and must be unique. The treeview .insert defaults to None (iid=None) if not specified.
By specifying the iid as an integer value as you inert rows you will always know which row you have (or need to get) to summarize.