How to close previous window on tkinter? - python

I'm trying to close the previous window when I click the button to go to the next window. I'm not being able to do it. What's wrong?
from tkinter import *
def newwindow2():
newwindow.destroy()
newwindow2 = tk.Toplevel()
newwindow2.title('Nível da grama região 3')
newwindow2.geometry('580x520')
labl3 = Label(newwindow2, text='A foto do nível da grama na região 3 foi tirada: \n', font=30).place(x=110, y=10)
tk.Button(newwindow2, text='Fim').place(x=250, y=470)
def newwindow():
janela1.destroy()
newwindow = tk.Toplevel()
newwindow.title('Nível da grama região 2')
newwindow.geometry('580x520')
labl2 = Label(newwindow, text='A foto do nível da grama na região 2 foi tirada: \n', font=30).place(x=110, y=10)
tk.Button(newwindow, text='Próximo', command=newwindow2).place(x=250, y=470)
janela1 = tk.Tk()
janela1.title('Nível da grama região 1')
janela1.geometry("580x520")
labl1=Label(janela1, text='A foto do nível da grama na região 1 foi tirada: ',font=30).place(x=110, y=10)
tk.Button(janela1, text='Próximo', command=newwindow).place(x=250, y=470)
janela1.mainloop()
As you can see I'm trying to use .destroy() but it's not working. Any solutions? I'm just starting to learn Python so I'm aware this might be very simple. Thanks for the help!

I see see several problems. The main one being that you can't call newwindow.destroy() because newwindow is a function not a tk.Toplevel widget. Another is the janela1.destroy() destroying itself, and it's the root window.
Instead of destroying windows, you can just withdraw() them. Here's code that I think does what you want:
from tkinter import *
import tkinter as tk
def make_newwindow2():
# newwindow.destroy()
global newwindow2
newwindow.withdraw()
newwindow2 = tk.Toplevel()
newwindow2.title('Nível da grama região 3')
newwindow2.geometry('580x520')
labl3 = Label(newwindow2,
text='A foto do nível da grama na região 3 foi tirada:\n', font=30)
labl3.place(x=110, y=10)
tk.Button(newwindow2, text='Fim', command=root.quit).place(x=250, y=470)
def make_newwindow():
# janela1.destroy()
global newwindow
root.withdraw()
newwindow = tk.Toplevel()
newwindow.title('Nível da grama região 2')
newwindow.geometry('580x520')
labl2 = Label(newwindow,
text='A foto do nível da grama na região 2 foi tirada:\n', font=30)
labl2.place(x=110, y=10)
tk.Button(newwindow, text='Próximo', command=make_newwindow2).place(x=250, y=470)
root = tk.Tk()
root.title('Nível da grama região 1')
root.geometry("580x520")
labl1 = Label(root, text='A foto do nível da grama na região 1 foi tirada: ', font=30)
labl1.place(x=110, y=10)
tk.Button(root, text='Próximo', command=make_newwindow).place(x=250, y=470)
root.mainloop()
Something else I changed, even though it wasn't strictly necessary, was how you were assigning the result of calling place() to the names of a widgets. Since place() (and pack() and grid()) always return None, that's the value the variable will end up with — which is never what you'd want. You're getting away with it here, but only because those names aren't referenced again.

Related

Problems when positioning buttons with tkinter

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

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

Why does the button stay pressed in my code?

I really know why mi button stay pressed, the qestion is more like: How can I avoid it? The source code is below, thanks:
import tkinter as tk
from tkinter import filedialog as fd
# creacion de cada venta
# ---ventana 1---
class Window1(tk.Frame):
final_path = ""
def __init__(self, parent):
# inicio y creacion del propio frame
tk.Frame.__init__(self, parent)
self.config(bg="#33ccff", width='990', height='250')
# primera etiqueta con valores
self.label1 = tk.Label(
self, text="Documento Seleccionado", bg="#33ccff")
# segunda etiqueta con texto variable
self.txt_carga = tk.StringVar()
self.txt_carga.set("Archivo no seleccionado")
self.label2 = tk.Label(self, textvariab=self.txt_carga, bg="#33ccff")
# primer boton de carga de documentos y funcion del boton
self.load_button = tk.Button(self, text="Cargar Documento")
# segundo boton de siguiente
self.next_button = tk.Button(self, text="Siguiente")
# Definicion de funciones (Con binding hay que añadir el evento al boton)
def function_load(event):
path = fd.askopenfile(filetype=(("Excel", ".xlsx"), ("CSV", ".csv"), ("Todos los Archivos", "*.*")))
self.final_path = str(path.name)
self.txt_carga.set(path.name)
def function_next(event):
print(self.final_path)
# binding: de esta manera se llama a las funciones de los botones al final de forma
# que queda mas ordenado, (x,y) -> x = tipo de evento, y = funcion donde se define
self.load_button.bind('<ButtonPress-1>', function_load)
self.next_button.bind('<Button-1>', function_next)
# instanciacion de los objetos en la ventana
self.label1.grid(row=0, column=0, columnspan=2, padx=200, pady=25)
self.label2.grid(row=1, column=0, columnspan=2, pady=25)
self.load_button.grid(row=2, column=0, pady=20)
self.next_button.grid(row=2, column=1, pady=20)
# ---ventana inicio------
class MainWindow(tk.Frame):
def __init__(self, parent, *args, **kwargs):
self.parent = parent
# necesario para que este se inicie como objeto de la clase Frame
tk.Frame.__init__(self, parent, *args, **kwargs)
# INSANCIAS
self.window1 = Window1(self) # instancia de la clase
self.window1.pack() # empaquetado de la clase
self.pack() # empaquetado propio
# creo el main del programa
if __name__ == "__main__":
root = tk.Tk()
MainWindow(root)
root.mainloop()
As you can see my program has a window in which I put a couple of Labels, and a couple of buttons. The problem is caused by the function asigned to the load_button (def function_load), because the filedialog opens but I suppose the process keeps running and that causes the button stay pressed.
You needn't to bind a event for your button widget if you want to do something when you press them,just set a command for it.And you have a spelling error in your code.Your final code:
import tkinter as tk
from tkinter import filedialog as fd
# creacion de cada venta
# ---ventana 1---
class Window1(tk.Frame):
final_path = ""
def __init__(self, parent):
# inicio y creacion del propio frame
tk.Frame.__init__(self, parent)
self.config(bg="#33ccff", width='990', height='250')
# primera etiqueta con valores
self.label1 = tk.Label(
self, text="Documento Seleccionado", bg="#33ccff")
# segunda etiqueta con texto variable
self.txt_carga = tk.StringVar()
self.txt_carga.set("Archivo no seleccionado")
self.label2 = tk.Label(self, textvariable=self.txt_carga, bg="#33ccff") # spelling error.
# primer boton de carga de documentos y funcion del boton
self.load_button = tk.Button(self, text="Cargar Documento",command=self.function_load) # add command
# segundo boton de siguiente
self.next_button = tk.Button(self, text="Siguiente",command=self.function_next) # add command
# Definicion de funciones (Con binding hay que añadir el evento al boton)
# binding: de esta manera se llama a las funciones de los botones al final de forma
# que queda mas ordenado, (x,y) -> x = tipo de evento, y = funcion donde se define
# instanciacion de los objetos en la ventana
self.label1.grid(row=0, column=0, columnspan=2, padx=200, pady=25)
self.label2.grid(row=1, column=0, columnspan=2, pady=25)
self.load_button.grid(row=2, column=0, pady=20)
self.next_button.grid(row=2, column=1, pady=20)
def function_load(self): # it can be a self.function
path = fd.askopenfilename(filetype=(("Excel", ".xlsx"), ("CSV", ".csv"), ("Todos los Archivos", "*.*")))
self.txt_carga.set(path)
def function_next(self):
print(self.final_path)
# ---ventana inicio------
class MainWindow(tk.Frame):
def __init__(self, parent, *args, **kwargs):
self.parent = parent
# necesario para que este se inicie como objeto de la clase Frame
tk.Frame.__init__(self, parent, *args, **kwargs)
# INSANCIAS
self.window1 = Window1(self) # instancia de la clase
self.window1.pack() # empaquetado de la clase
self.pack() # empaquetado propio
# creo el main del programa
if __name__ == "__main__":
root = tk.Tk()
MainWindow(root)
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