Related
i am trying to learn python from a book. I'm trying to do an exercise with tinker. Click on a button and advance to the limit of the window. Then always by clicking on the same button to advance the circle to the other side of the window. Thanks for your help.
from tkinter import *
def avance(n, g):
global x, y, step
# nouvelles coordonnées :
x[n] = x[n] + g # deplacement de l'axe des x
# déplacement du dessin dans le canevas :
can.coords(bille[n], x[n]-10, y[n]-10, x[n]+10, y[n]+10)
# affichage pour info du x:
Info.configure(text="Coordonnée x = " + str(x[n]))
i = 0
if x[n] >= 50:
while i <= 400:
step = +20
i = i+5
if x[n] >= 400:
step = -20
i = i-5
return step
def go():
avance(0, step)
bille = [0] # liste servant à mémoriser les références du cercle
x = [50] # X de départ
y = [100] # y de départ
step = 0 # "pas" de déplacement initial
# Construction de la fenêtre :
fen = Tk()
fen.title("avance quand on clique jusqu'à la limite de la fenêtre et revient")
Info = Label(fen) # pour afficher l'info du x
Info.grid(row=3, column=0)
# Canvas :
can = Canvas(fen, bg="white", width=400, height=200)
can.grid(row=2, column=0, columnspan=2)
bille[0] = can.create_oval(x[0]-10, y[0]-10, x[0]+10, y[0]+10,
fill="blue")
# bouton avance :
f = Frame(fen)
f.grid(row=4, column=0, sticky=W, padx=10)
Button(f, text="Go", fg='blue', command=go).pack(side=LEFT)
fen.mainloop()
the problem is that when the ball reaches the limit (first while loop) when it starts the second loop, it returns to the conditions of the first.
sorry for my English
thank for help
I solved my problem.
here is my solution
from tkinter import *
def avance(n, g):
global x, y, step
# nouvelles coordonnées :
x[n] = x[n] + g # deplacement de l'axe des x
# déplacement du dessin dans le canevas :
can.coords(bille[n], x[n]-10, y[n]-10, x[n]+10, y[n]+10)
# affichage pour info du x:
Info.configure(text="Coordonnée x = " + str(x[n]))
i = 0
if 5 >= x[n] < 400: # 5 superieur ou egale à x et x inferieur à 400 , execute la ligne suivante
step=+20
return step
if 5 <= x[n] >= 400: # 5 inferieur ou egale à x et x superieur ou egale à 400 , execute la ligne suivante
step = -20
return step
# x egale 50 execute le premier if..
def go():
avance(0, step)
step = 0 # variable pour le pas d'avancement
bille = [0] # liste servant à mémoriser les références du cercle
x = [5] # X de départ
y = [100] # y de départ
# "pas" de déplacement initial
# Construction de la fenêtre :
fen = Tk()
fen.title("avance quand on clique jusqu'à la limite de la fenêtre et revient")
Info = Label(fen) # pour afficher l'info du x
Info.grid(row=3, column=0)
# Canvas :
can = Canvas(fen, bg="white", width=400, height=200)
can.grid(row=2, column=0, columnspan=2)
bille[0] = can.create_oval(x[0]-10, y[0]-10, x[0]+10, y[0]+10,
fill="blue")
# bouton avance :
f = Frame(fen)
f.grid(row=4, column=0, sticky=W, padx=10)
Button(f, text="Go", fg='blue', command=go).pack(side=LEFT)
fen.mainloop()
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.
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()
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()
I'm new to the code and I'm experiencing with tkinter, and I'm making a money counter with tkinter and to make it happen on screen i need to make a Label change it's text properties form one text to another one with a button, the problem is that it works on console, but when I try to make it change on tkinter it freezes and doesn't change. The parts I'm talking about are, the ones highlighted with (----code----).
I know that the problem concerns threading, due to the fact that the programs runs when I remove the keyboard.is_pressed, but i don't actually know how to implement it.
from tkinter import *
import keyboard
import sys
import time
import winsound
raiz = Tk()
raiz.title("Contador de Divisas")
raiz.iconbitmap("MonedaContador.ico")
Total = 0
def contador_de_espacios(divisa, diccionario):
global lista
global Total
global posiciones_en_diccionario
Numero = ""
Contador = 0
Escape = 0
Cambiar = 0
Multiplicador = divisa * 5
Nombre = str(divisa)
suma_lista = 0
if divisa > 2:
Nombre = (" billetes de " + Nombre + " Euros.")
else:
Nombre = (" Monedas de " + Nombre + " Euro/s.")
eleccion.config(text = Nombre)----------------------------
while True:
if keyboard.is_pressed('space'):
Control = 0
Contador += 1
Numero = str(Contador)
Marcador.config(text = Numero)-------------------------------
winsound.Beep(2500, 200)
time.sleep(0.25)
def clasificador_de_divisa(boton):
global posiciones_en_lista
posicion = posiciones_en_lista.get(str(boton))
contador_de_espacios(boton, posicion)
myframe = Frame()
myframe.pack()
myframe.config(width = "650", height = "350")
explicacion = Label(myframe, text = "Esto es un contador de divisas en euros. Por cada grupo de 5 monedas/billetes le das una vez al espacio, cosa que añadirá 1 monton de 5 monedas/billetes al contador.")
explicacion.grid(row = 0, column = 0, padx = 10, pady = 30, columnspan = 9)
explicacion.config(font = (30))
eleccion = Label(myframe)--------------------------------------
eleccion.grid(row = 1, column = 2, padx = 10, pady = 30, columnspan = 5)
eleccion.config(font = (30))
Marcador = Label(myframe, text = "0")
Marcador.grid(row = 2, column = 3, pady = 30, columnspan = 3, rowspan = 1)
Marcador.config(font=("Arial",100), bg = "black", fg = "white")
boton1euro = Button(myframe, text = "1 Euro", width = 10, command = lambda:clasificador_de_divisa(1))
boton1euro.grid(row = 3, column = 0, padx = 10, pady = 30)
raiz.mainloop()
The expected output is the program changing the Label, but it doesn't and freezes.