Python: calling function inside if statement from another File - python

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()

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()

Problem with variable for if statement in tkinter

Hy everyone, i've a problem with my script, because when i launch it for testing and press the L0 button i receive this error message:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/init.py", line 1705, in call
return self.func(*args)
File "nucleo.py", line 33, in spegni
value = int(previous_state.get()) UnboundLocalError: local variable 'previous_state' referenced before assignment
I show my full code:
import serial
import random
import time
from tkinter import *
from tkinter import messagebox
import os
previuos_state=0
def accendi():
if previous_state == 0:
TimeDelay = random.randrange(10,20)
time.sleep(TimeDelay)
ser.write('L1'.encode())
previous_state = 1
USER_TIME = list(ser.read(5).decode("utf8"))
if USER_TIME[0] == 'T':
USER_TIME = str(USER_TIME[1])+str(USER_TIME[2])+str(USER_TIME[3])+str(USER_TIME[4])
print(str(int(USER_TIME,16))+" ms")
else:
print("Errore in ricezione")
else:
messagebox.showwarning("Attenzione", "Spegnere led per iniziare un nuovo test")
def spegni():
if previous_state == 1:
TimeDelay = random.randrange(10,20)
time.sleep(TimeDelay)
ser.write('L0'.encode())
previous_state = 0
USER_TIME = list(ser.read(5).decode("utf8"))
if USER_TIME[0] == 'T':
USER_TIME = str(USER_TIME[1])+str(USER_TIME[2])+str(USER_TIME[3])+str(USER_TIME[4])
print(str(int(USER_TIME,16))+" ms")
else:
print("Errore in ricezione")
else:
messagebox.showwarning("Attenzione", "Accendere led per iniziare un nuovo test")
finestra=Tk()
finestra.geometry("520x230")
finestra.title("Misuratore di riflessi")
testo=Label(finestra, text="Premere il pulsante L0 se il LED è acceso\nPremere il pulsante L1 se il LED è spento\nPremere EXIT per uscire")
testo.grid(row=0, column=0, columnspan=3)
tasto1=Button(finestra, text="L0", command=spegni)
tasto1.grid(row=3, column=0)
tasto2=Button(finestra, text="L1", command=accendi)
tasto2.grid(row=3, column=2)
lista=Listbox(finestra)
lista.insert(END, "uno", "due", "tre", "quattro", "cinque", "sei", "sette", "otto")
lista.grid(row=0, column= 3, columnspan=5, rowspan=5)
tasto3=Button(finestra, text="EXIT", command=exit)
tasto3.grid(row=4, column=1)
finestra.mainloop()
I don't understand why i can't use the variable "previuous_state", in the functions.
previous state is misspelled in its initial declaration
import serial
import random
import time
from tkinter import *
from tkinter import messagebox
import os
previuos_state=0
This makes your checks at the start of your functions fail as the variable is not declared
The right code:
import serial
import random
import time
from tkinter import *
from tkinter import messagebox
import os
previous_state=0
def stampa():
print(previous_state)
def accendi():
if previous_state == 0:
TimeDelay = random.randrange(10,20)
time.sleep(TimeDelay)
ser.write('L1'.encode())
previous_state = 1
USER_TIME = list(ser.read(5).decode("utf8"))
if USER_TIME[0] == 'T':
USER_TIME = str(USER_TIME[1])+str(USER_TIME[2])+str(USER_TIME[3])+str(USER_TIME[4])
print(str(int(USER_TIME,16))+" ms")
else:
print("Errore in ricezione")
else:
messagebox.showwarning("Attenzione", "Spegnere led per iniziare un nuovo test")
def spegni():
if previous_state == 1:
TimeDelay = random.randrange(10,20)
time.sleep(TimeDelay)
ser.write('L0'.encode())
previous_state = 0
USER_TIME = list(ser.read(5).decode("utf8"))
if USER_TIME[0] == 'T':
USER_TIME = str(USER_TIME[1])+str(USER_TIME[2])+str(USER_TIME[3])+str(USER_TIME[4])
print(str(int(USER_TIME,16))+" ms")
else:
print("Errore in ricezione")
else:
messagebox.showwarning("Attenzione", "Accendere led per iniziare un nuovo test")
finestra=Tk()
finestra.geometry("520x230")
finestra.title("Misuratore di riflessi")
testo=Label(finestra, text="Premere il pulsante L0 se il LED è acceso\nPremere il pulsante L1 se il LED è spento\nPremere EXIT per uscire")
testo.grid(row=0, column=0, columnspan=3)
tasto1=Button(finestra, text="L0", command=spegni)
tasto1.grid(row=3, column=0)
tasto2=Button(finestra, text="L1", command=accendi)
tasto2.grid(row=3, column=2)
lista=Listbox(finestra)
lista.insert(END, "uno", "due", "tre", "quattro", "cinque", "sei", "sette", "otto")
lista.grid(row=0, column= 3, columnspan=5, rowspan=5)
tasto3=Button(finestra, text="EXIT", command=exit)
tasto3.grid(row=4, column=1)
tastoo=Button(finestra, text="STAMPA", command=stampa)
tastoo.grid(row=1, column=1)
finestra.mainloop()
I continue to try but i can't use the variable for the if

How to print through local or network printer in tkinter

I want to select one of installed printer on my computer and print through it but my combobox doesn't display the printers on my machine but rather print to my terminal in my IDE .
Have been trying this for days with arriving at the solution to do this.Have installed the win32print module to after reading about it.This my code below:
from tkinter import *
from tkinter import ttk
import win32print
def installed_printer():
printers = win32print.EnumPrinters(2)
for p in printers:
return(p)
def locprinter():
pt = Toplevel()
pt.geometry("250x250")
pt.title("choose printer")
LABEL = Label(pt, text="select Printer").pack()
PRCOMBO = ttk.Combobox(pt, width=35,
textvariable=installed_printer).pack()
BUTTON = ttk.Button(pt, text="refresh",
command=installed_printer).pack()
root = Tk()
root.title("printer selection in tkinter")
root.geometry("400x400")
menubar = Menu(root)
root.config(menu=menubar)
file_menu = Menu(menubar)
menubar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="printer", command=locprinter)
LAB = Label(root, text="Comment")
T2 = Text(root, width=40, height=10)
def INFO():
print(T2.get("1.0", END))
Print_Button = Button(root, text ="Print", command =
INFO).place(x=180,y=250)
LAB.pack()
T2.pack()
root.mainloop()
How can i achieve this as i want to print the content in my Text box with tkinter framework.
Is this what you wanted to create?
from tkinter import *
from tkinter import ttk
import win32api
import win32print
import tempfile
def installed_printer():
printers = win32print.EnumPrinters(2)
for p in printers:
return(p)
printerdef = ''
def locprinter():
pt = Toplevel()
pt.geometry("250x250")
pt.title("choose printer")
var1 = StringVar()
LABEL = Label(pt, text="select Printer").pack()
PRCOMBO = ttk.Combobox(pt, width=35,textvariable=var1)
print_list = []
printers = list(win32print.EnumPrinters(2))
for i in printers:
print_list.append(i[2])
print(print_list)
# Put printers in combobox
PRCOMBO['values'] = print_list
PRCOMBO.pack()
def select():
global printerdef
printerdef = PRCOMBO.get()
pt.destroy()
BUTTON = ttk.Button(pt, text="Done",command=select).pack()
root = Tk()
root.title("printer selection in tkinter")
root.geometry("400x400")
menubar = Menu(root)
root.config(menu=menubar)
file_menu = Menu(menubar)
menubar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="printer", command=locprinter)
LAB = Label(root, text="Comment")
T2 = Text(root, width=40, height=10, wrap=WORD)
def INFO():
printText = T2.get("1.0", END)
print(printText)
print(printerdef)
filename = tempfile.mktemp(".txt")
open(filename, "w").write(printText)
# Bellow is call to print text from T2 textbox
win32api.ShellExecute(
0,
"printto",
filename,
'"%s"' % win32print.GetDefaultPrinter(),
".",
0
)
Print_Button = Button(root, text ="Print", command=INFO).place(x=180,y=250)
LAB.pack()
T2.pack()
root.mainloop()

tkinter labels dont show

So I got the assignment to make a small Bingo App (Windows btw) after I followed a few webinars on Tkinter GUI and some Googling.
I have made successfull little apps that worked correctly, but this time I try to make it with knowledge I think I have.
Anyway, in that Bingo app, I want 50 labels that represent 50 numbers of the Bingo card, 5 rows of 10 numbers.
I know how to align them, but they need to show up first.
Can you look at my code and assess what I do wrong?
Ignore the many Dutch comments :)
'''
iWMMMM0.
XM#o:..iIMM.
MM. :XC17, YM8
M# v#9. .W# ,M,
#M 7#i ,0$: M0 MM
.M. #7 M#t, ME MQ
MM iM. #$Ci$Q ;M#CCY:.
CM ,M, b#$; v;7IEW#MMM#1
MQ WQ .tE0Q2nCCYc;i,:7#MMi
:M #b . .. .:YCb0U: YMM.
WM E#i .... ,i: ,b#; bMQ,SbW06i
oM MC ... MME9#$Y . .#b SM#b2tob#MM1
Mi #7 ... #M .v iMt ... #X :CoUzt: :MM, nWM#Bc :nQ#$Ui
M: #Y .. M9 MM# b# ... Zb1#Zi. .;Z#Y SMi MM#t;vCMM,CMM0C77bMM8
M, #7 .. #6 Y7 ;Mn ... #QB. ,#b ZM MM .n9U; bMM. ;z2U7 MM
M: #Y ., #9.;tQQv ... ;MQ, :#; Mv MM X$: M; , ;$2. 7#i M8
M: #7 .. #BW1i ..,:Y$Mt$ MX MMtiEM: E#: ZME,.W$c ; c# .M
M: #Y ., ME .. .ZMM8o89 QM. i;U## .Zb7: ,BBYzQ bM# Mi M
Mi #X .. M, iMM#WS :bWQb, ,#M1;IoIX 1#c bMMX iM I#E$CM M, M
.MM #7 ., Mn EM8AEE#: . v$AWQ#$Q#MMIWz, ;$Z$ MMzW2 M# $ZY$C bM CM
MZ ib#i .. ##. ;t $z#. ., CWUWnE$b7: :Y #$c MEYY .MM8 :; vM. M1
iM iMi .., #bWI,..M#i#C .., Mv i#E. UMM2 #BC oC;tMMCES .#M MM
MY E0 ... S#i:Z$MZ .Mv ... M8 7WEz MnZo #obUA: ic.7bEW$#M#C iMM
CMi I#; .. b#; $$ ... ,MQ 7$Zz #zbz #IXW#E69z. 80 ::iAMM;
iM$ .$Qi . :Z$Q0Q#6. ... MQ0 C$b1 MtQ7 YZWW,.c$## MC MMM#b.
MM7 iBWv. .., .M#7$ v$8; vQ0:iCAM: :#bM0 nMU BM
:MM1 .6$Q7: ;MMS:Q7 ##i12EMzEESB# .7:,,2M# MM
,MM#: ,1E$BQbZ6EBMM#; iQQ##B$72n7i.,vo tQQIZQ$WC .#MQ
6MM#o;,,:ivY;i,,iEMM...,,:iC2Q#MMMQ$M$..,i::,;9MMZ
YIEbEAU269086, ;Bb08bAz;:. 7QbEZb8boi
'''
##Basale geimporteerde functies
from tkinter import*
#self=()
#Importeert de randomfucntie
#import random
#Importeert de Python Debugger
#Runnen met pdb.run
#import pdb
#Importeert de PIL Python Image Library
#from PIL import Image, ImageTK
#image = image.open("bestandsnaam.jpg")
#photo ImageTK.PhotoImage(image)
#Een afbeelding op een label
#label = Label(image=photo(als photo de naam van de variable is))
#label.image = photo (bewaren als referentie?<- geen idee nog)
'''
#=# Start van metainfo class/klasse
class MetaBingPy():
def __init__(self):
super(MetaBingPy, self).__init__()
self.parent = parent
self.pack()
MetaBingPy.BingoPyC(self)
##Functie voor random number generator
def BingoPyC:
self.root = Tk()
self.root.title("Python Bingo")
#=#Einde metainfo class
'''
###def random.randint(1,50)
#####of# randrange(1,50)
##GUI voor BingPy, moet root heten. Geen eigen naam, zoals:
##BingPyGUI wat ik had.
root = Tk()
root.wm_title("Bingo Python")
root.wm_maxsize("800","600")
root.wm_minsize("800","600")
#root.wm_grid(baseWidth="800", baseHeight="800")
#root.grid("800x800")
#_tkinter.TclError: wrong # args: should be "wm grid window ?baseWidth baseHeight
#widthInc heightInc?"
##self.title="Bingo Python"
###GUI voor BingPy code, altijd afsluiten met:
###bovenaan
root.mainloop()
'''
#Algemene Python Bingo klasse
class BingoPy
def
'''
#Labels voor alle nummers (50)
label1 = Label(root, text="1jghjgjkhjhg")
label1.grid()
label1.pack()
label2 = Label(root, text="2")
label2.grid()
label2.pack()
label3 = Label(root, text="3")
label3.grid()
label3.pack()
label4 = Label(root, text="4")
label4.grid()
label4.pack()
label5 = Label(root, text="5")
label5.grid()
label5.pack()
label6 = Label(root, text="6")
label6.grid()
label6.pack()
label7 = Label(root, text="7")
label7.grid()
label7.pack()
label8 = Label(root, text="8")
label8.grid()
label8.pack()
label9 = Label(root, text="9")
label9.grid()
label9.pack()
label10 = Label(root, text="10")
label10.grid()
label10.pack()
label11 = Label(root, text="11")
label11.grid()
label11.pack()
label12 = Label(root, text="12")
label12.grid()
label12.pack()
Label13 = Label(root, text="13")
Label13.grid()
Label13.pack()
label14 = Label(root, text="14")
label14.grid()
label14.pack()
label15 = Label(root, text="15")
label15.grid()
label15.pack()
label16 = Label(root, text="16")
label16.grid()
label16.pack()
label7 = Label(root, text="17")
label17.grid()
label17.pack()
label18 = Label(root, text="18")
label18.grid()
label18.pack()
label19 = Label(root, text="19")
label19.grid()
label19.pack()
label20 = Label(root, text="20")
label20.grid()
label20.pack()
label21 = Label(root, text="21")
label21.grid()
label21.pack()
label22 = Label(root, text='22')
label22.grid()
label22.pack()
label23 = Label(root, text="23")
label23.grid()
label23.pack()
label24 = Label(root, text="24")
label24.grid()
label24.pack()
label25 = Label(root, text="25")
label25.grid()
label25.pack()
label26 = Label(root, text="26")
label26.grid()
label26.pack()
label27 = Label(root, text="27")
label27.grid()
label27.pack()
label28.Label(root, text="28")
label28.grid()
label28.pack()
label29 = Label(root, text="29")
label29.grid()
label29.pack()
label30 = Label(root, text="30")
label30.grid()
label30.pack()
label31 = Label(root, text="31")
label31.grid()
label31.pack()
label32 = Label(root, text="32")
label32.grid()
label32.pack()
label33 = Label(root, text="33")
label33.grid()
label33.pack()
label34 = Label(root, text="34")
label34.grid()
label34.pack()
label35 = Label(root, text="35")
label35.grid()
label35.pack()
label36 = Label(root, text="36")
label36.grid()
label36.pack()
label37 = Label(root, text="37")
label37.grid()
label37.pack()
label38 = Label(root, text="38")
label38.grid()
label38.pack()
label39 = Label(root, text="39")
label39.grid()
label39.pack()
label40 = Label(root, text="40")
label40.grid()
label40.pack()
label41 = Label(root, text="41")
label41.grid()
label41.pack()
label42 = Label(root, text="42")
label42.grid()
label42.pack()
label43 = Label(root, text="43")
label43.grid()
label43.pack()
label44 = Label(root, text="44")
label44.grid()
label44.pack()
label45 = Label(root, text="45")
label45.grid()
label45.pack()
label46 = Label(root, text="46")
label46.grid()
label46.pack()
label47 = Label(root, text="47")
label47.grid()
label47.pack()
label48 = Label(root, text="48")
label48.grid()
label48.pack()
label49 = Label(root, text="49")
label49.grid()
label49.pack()
label50 = Label(root, text="50")
label50.grid()
label50.pack()
#Maakt het rood (en als het mogelijk is: doorstrepen) als het getrokken is
#Waarde-return in veld + niet meer zelfde nummer kunnen kiezen
#--------------------------------------------------------------------------
#Knoppen voor afsluiten en nieuw getal
##Afsluiten
#def bingoclose():
# print("Bingo Afsluiten")
'''
bAfsluiten = Button(root,text"Sluit Bingo Af")
bAfsluiten.pack()
'''
'''
{
'title' : ['BingPy'],
'summary' : ['Simple Bingo Python Application with rand.num generator'],
'authors' : ['Thomas']
#'date' : ['2015']
'base_url' : ['http://www.rainydays.eu']
}
'''
'''
Info en weblinks:
https://docs.python.org/3/library/random.html?highlight=random#module-random
http://infohost.nmt.edu/tcc/help/pubs/tkinter/tkinter.pdf (Python 2.7!)
https://wiki.scinet.utoronto.ca/wiki/images/4/41/Pwcgui.pdf
http://stackoverflow.com/questions/3643235/how-to-add-a-margin-to-a-tkinter
-window Margins in Python (padx, pady)
'''
You need to learn about data structures, like list.
You had root.mainloop() early on in the code. That starts a loop. Nothing after that is executed until the window is closed, which means it has to be at the end.
Choose one geometry manager. You can't use both grid() and pack() in the same parent widget, much less on the same child widget.
You had some typos, like label7 = instead of label17 =, and label28.Label instead of label28 = Label. Most of these would never have happened if you had used a list.
Obviously, 50 labels won't fit in a single column in a window of that size. You've got some decisions ahead of you involving window size, label placement, possible scrollbar, and so on.
The resulting code taking into account all these points (except the last) is shown below.
from tkinter import *
root = Tk()
root.wm_title("Bingo Python")
root.wm_maxsize("800","600")
root.wm_minsize("800","600")
labels = [Label(root, text=i) for i in range(1, 51)]
for label in labels:
label.pack()
root.mainloop()

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()

Categories