Problems when positioning buttons with tkinter - python

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.

Related

how can I set that a button give me the answer of the entry in the tkinter?

i tried to make a simple code to do a joke with my friends. It's based in: they entry with her names, and when they clicked in button, a answer appears. Before this, i maked a simple code based in: if(xxxx), so print(xxxxx). Now, i using tkinter to give a GUI to my code. But, i don't know how make the button do this when i push him.
from tkinter import *
def piadinhas():
nome = input('Say your name! ')
if nome == 'Fabricia' or nome == 'fabricia':
print('*****************')
elif nome == 'Roberto' or nome == 'roberto':
print('Para de camperar na caixa da B')
elif nome == 'Lucas' or nome == 'lucas':
print('Oi, mozão!')
elif nome == 'Leonardo' or nome == 'leonardo':
print('Porque você não planta *********************?')
elif nome == 'Montanha' or nome == 'montanha':
print('Seu nome é montanha, ******?')
elif nome == 'Marcos' or nome == 'marcos' or nome == 'Marcos Cesar':
print('SOCRAAAAAAAAAAAAAAAAAAAAAAAAM, e aquela festinha lá, hein!?')
elif nome == 'Lorenzo' or nome == 'lorenzo' or nome == 'oznerol':
print('Qual o seu dom?')
elif nome == 'Camiran':
print('Quando será o próximo meme de marea pegando fogo?')
else:
print('Você não é um dos ****!')
janela = Tk()
janela.title('Aplicativo de Adjetivos Carinhosos')
janela.geometry('300x300')
janela.config(background='#dde')
texto_apresentacao = Label(janela, text='Eu sei quem você é!', background='#dde')
texto_apresentacao.grid(column=0, row=0, padx=85, pady=15)
texto_orientacao = Label(janela, text='Say Your Name, Dont Lie', background='#dde')
texto_orientacao.grid(column=0, row=1, padx=85, pady=15)
entrada_nome = Entry(janela)
entrada_nome.grid(column=0, row=2, padx=85, pady=15)
botao_resultado = Button(janela, width=20, height=2)
botao_resultado.grid(column=0, row=3, padx=85, pady=15)
janela.mainloop()
Who can help a poor beginner?
You should have done a little research before asking. Learn about how-to-ask. And Refer here to know about the Entry widget in Tkinter.
Declare a string variable (needed to store the user's input.) Then, make that string variable as the Entry box's textvariable. And, set "command=piadinhas" so that the function is called on clicking that button.
inp = StringVar()
entrada_nome = Entry(janela,textvariable = inp)
...
botao_resultado = Button(janela, width=20, height=2, command=piadinhas)
Also, make these changes in your function:
def piadinhas():
nome = inp.get()
Read the documentation to know more.

delete a frame and update the index

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

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

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