Closed. This question is not written in English. It is not currently accepting answers.
Stack Overflow is an English-only site. The author must be able to communicate in English to understand and engage with any comments and/or answers their question receives. Don't translate this post for the author; machine translations can be inaccurate, and even human translations can alter the intended meaning of the post.
Closed 2 days ago.
Improve this question
import os
import tkinter as tk
import subprocess
def getEntry():
res = myEntry.get()
return res
def getEntryFil():
LienDossier = myEntryFil.get()
return os.listdir(LienDossier)
# trouver le chemin d’un fichier spécifique sur notre machine
def findfile(name, path):
for dirpath, dirname, filename in os.walk(path):
if name in filename:
return os.path.join(dirpath, name)
# création fenetre
root = tk.Tk()
root.geometry('1000x1000')
# Ajout d'un titre à la fenêtre principale :
root.title("Recherche")
myEntryFil = tk.Entry(root, width=70)
myEntryFil.pack(pady=60)
btn1 = tk.Button(root, height=1, width=10, text="Lire", command=getEntryFil)
btn1.pack()
myEntry = tk.Entry(root, width=40)
myEntry.pack(pady=20)
btn = tk.Button(root, height=1, width=10, text="Lire", command=getEntry)
btn.pack()
# Affichage de la fenêtre créée :
root.mainloop()
# Barre de recherche recup le texte dans var res et lancement du fichier concerné
A = getEntryFil()
res = getEntry()
Taille = len(A) #taille de la liste
#affichage de la liste de fichier contenus dans le repertoire
Lbl = tk.Listbox(root) #creation de la liste
#création de lignes de la liste
for i in range(Taille):
Ele = A[i]
Lbl.insert(i, Ele) #inster l'element i de la liste A
Lbl.pack()
print("----------->",res)
if res in A:
# execute la fonction pour trouver un chemin
filepath = findfile("res", "/")
#lancer une appli
subprocess.Popen(filepath, shell=True)
else:
print("Faux")
Bonjour,
Je suis un débutant en python.
Quand je lance le code la fenetre Tkinter se lance bien mais quand j'essaie d'interagire il ne se passe rien je pense que c'est dus car mon code est en dehors du
root = tk.Tk()
est du
root.mainloop()
Mais quand je met mon code python a l'interieur il me dit : FileNotFoundError: [WinError 3] Le chemin d’accès spécifié est introuvable: ''
car pour avoir ce chemin d'accès il faut remplir un champ de texte dans ma page tkinter et appuyer sur un bouton pour exécuter la fonction prévue a cet effet. Mais comme le code est a l'interieur de la boucle de la fenètre tkinter je n'ai pas le temps de remplire le champ de texte.
Peut-être faut t'il crée une autre fonction je sait pas je suis au pied du mur.
Pouvez vous m'aider s'il vous plait.
J'ai essayé de changer l'ordre de mes bloc de code mais pas d'effet.
Related
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.
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()
def next_turn():
global tab, tab2, x, y, test
test = test + 1
tab2 = [[0 for i in range(10)] for j in range(10)]
for y in range(10):
for x in range(10):
compter_cellules_voisines(y, x)
tab = tab2
adapte_dessin()
# Boutons sur la fenêtre pour faire un tour suivant sur la grille et pour nettoyer la grille
clr = Button(fen, text = 'Nettoyer le plateau', command = clear)
clr.pack(side = RIGHT, padx = 20, pady = 200)
etape = Button(fen, text = 'Tour suivant', command = next_turn)
etape.pack(side = RIGHT, padx = 10)
creation_lignes()
Canevas.bind('<Button-1>', Clic)
creer_tableau()
fen.mainloop()
I use this method for Game of Life but I would like to automatize the steps. I tried to change the next_step but it doesn't work.
Could you help me please?
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 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.