Close TopLevel window after command - python

I'm doing a simple compressor in Python for a school assignment, my problem here is that when you enter the name of the file, a little window has to appear with a button that will execute the tar command, I want that window to close after it does the command but I dont know why, here's my code
def crea_arxiu():
global aux
if v.get() is 1 or v.get() is 2 or v.get() is 3 or v.get() is 4:
f = open('fitxers.txt','w')
for i in range(llista2.size()):
f.write(llista2.get(i)+'\n')
f.close()
print 'Arxius a comprimir:',llista2.size()
obre_finestra()
if aux is 1:
print 'AUX IS TRUE'
subprocess.call(['rm','fitxers.txt'])
else:
print 'Escolleix una opcio'
#Aquest mètode crea i mostra la pantalla per guardar el nom
#i i la finestra amb la comanda que executara
def obre_finestra():
global aux
ruta_text = StringVar()
finestra2=Toplevel(finestra)
finestra2.minsize(0,0)
finestra2.title('Comanda a executar:')
ruta = Label(finestra2, width=60, relief=SUNKEN, textvariable=ruta_text)
ruta.pack(side=LEFT)
boto = Button(finestra2, text = 'Executar', command = lambda: executar_commanda(nom_arxiu, tipus_comp))
boto.pack(side = RIGHT)
nom_arxiu = tkFileDialog.asksaveasfilename(title='Guardar com')
if v.get() is 1:
tipus_comp = 'cf'
nom_arxiu = nom_arxiu+'.tar'
elif v.get() is 2:
tipus_comp = 'czf'
nom_arxiu = nom_arxiu+'.tgz'
elif v.get() is 3:
tipus_comp = 'cjf'
nom_arxiu = nom_arxiu+'.tbz'
elif v.get() is 4:
tipus_comp = 'cJf'
nom_arxiu = nom_arxiu+'.txz'
ruta_text.set('tar '+tipus_comp+' '+nom_arxiu+' '+'fitxers de la llista')
if aux is 1:
finestra2.destroy()
def executar_commanda(nom,tipus_comp):
global aux
aux = 1
subprocess.call(['tar',tipus_comp,nom,'-T','fitxers.txt'])
The order of the functions is: crea_arxiu -> obre_finestra (summons the asksaveasfilename and the little window) , and when i press 'Execute' does executar_commanda and then i want the window to be killed
Before entering the name of the file:
http://imgur.com/KOgxIe3
After the name is given:
http://imgur.com/zDB5Bbs
So at the end I just want the path window to be closed after it does de 'Executar' button, so much thank you guys and sry for my english not being so good ^^'

Related

BUTTON NOT SUBMITING DATA

I'm creating a GUI and I had an issue. My GUI is going to interact with the users, so when the user's inputs are written they have to be saven in a variable. I created a button to do this submition, but it's not working. The problem is in the sg.Button('SubmitData', visible=False) Does anyone knows why?
This is my code:
def window():
# Definindo o fundo da tela como preto
sg.theme('Black')
# Declarando o logo da mercedes
myImg = sg.Image(filename='logo_meca_pret.png',size=(200,200))
# Declarando os outputs
output = sg.Text(font=("Arial",20),key="output")
output2 = sg.Text(font=("Arial",20),key="output2")
output3 = sg.Text(font=("Arial",20),key="output3")
output4 = sg.Text(font=("Arial",20),key="output4")
layout = [
[myImg,sg.Text('PROGRAMA DE TREINAMENTOS',font=("Arial",60),justification="center")],
[sg.Text("Passe o cracha no leitor: ",font=("Arial",20)),sg.InputText(size=(60),key="ID")],
[sg.Text("Escreva seu nome: ",font=("Arial",20),visible=False,key="NAMETEXT"),sg.InputText(size=(60),visible=False,key="NAME")],
[sg.Text("Digite seu setor(111/112/113): ",font=("Arial",20),visible=False,key="SECTIONTEXT"),sg.Input(size=(5),visible=False,key="SECTION")],
[sg.Button('SubmitData', visible=False)],
[output],
[output2],
[output3,sg.InputText(size=(1),key="w_a",visible=False)],
[output4],
[sg.Text("CLIQUE NO BOTAO PARA ABRIR AS TELAS DOS TUTORIAIS",font=("Arial",30),visible=False,key="BOTAOW3"),sg.Button("W3",visible=False)],
[sg.Button('Submit', visible=False, bind_return_key=True)]
]
window = sg.Window('PROGRAMA DE TREINAMENTOS MERCEDES BENZ', layout,element_justification="center").Finalize()
window.Maximize()
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Cancel': # if user closes window or clicks cancel
break
#print('You entered ', values[0])
if event == 'Submit':
ID = values["ID"]
ID = ID.upper()
if is_registered(ID) == True:
name,section = current_user_data(users_df,ID)
output.update(f"Ola, {name}, bem vindo ao programa de treinamento Mercedes Benz Brasil!\n")
videos = videos_to_watch(section,ID)
if is_list_empty(videos,section,ID) == True:
output2.update("Nao ha novos tutoriais disponiveis.")
output3.update("Deseja assistir algum tutorial novamente (S/N)?")
window['w_a'].update(visible = True)
w_a = values["w_a"]
if w_a == "s" or w_a == "S":
# abre a tela com todos os tutoriais da pasta daquela secao
window2()
if w_a == "n" or w_a == "N":
# usa esses comandos para limpar a tela, para que um novo usuario use
window.find_element("ID").update("")
window.find_element("output").update("")
window.find_element("output2").update("")
window.find_element("output3").update("")
window.find_element("w_a").update("")
window['w_a'].update(visible = False) # deixa o input do w_a invisivel de novo
window.find_element("output4").update("")
else:
# se tiverem videos a serem assistidos abrir a WINDOW3
window["BOTAOW3"].update(visible = True)
window["W3"].update(visible = True)
if event == "W3":
# window3()
print("lalala")
else:
window["NAMETEXT"].update(visible = True)
window["NAME"].update(visible = True)
window["SECTIONTEXT"].update(visible = True)
window["SECTION"].update(visible = True)
window["SubmitData"].update(visible = True)
if event == 'SubmitData' :
name = values["NAME"]
name = name.title()
section = values["SECTION"]
output.update(f"Ola, {name}, bem vindo ao programa de treinamento Mercedes Benz Brasil!\n")
The output that I want is:
OUTPUT IMAGE

Problem with writing to file second time, Python3

I have created a phonebook with tkinker using Python 3.6
When I add persons to phonebook it save it to a file.
When I load the program again it loads the file as it should.
If I add 2 person at first run, all works fine.
Second run, I add one person and it adds an empty line at index 1 and adds the person below as it should.
Third run, I add one person, it adds a new line at index 1 and a person last in the list.
Now I get 2 empty lines.
I can't figure out why it creates an empty space at index 1 . It should not do it.
Here is the code, comments are in Swedish so sorry about it.
How I write to the file is in function lägg_till()
It will auto create kontakter.txt when you run it first time.
"Lägg till" means add in Sweden and "Avsluta" is quit the program.
from tkinter import *
import os.path
root = Tk()
root.geometry("640x640+200+100")
root.title("Telefon listan")
def avsluta():
quit()
def spara():
#Spara kontakter till fil.
name = entry_1.get()
mobil = entry_2.get()
if name == "" or mobil == "" :
pass
else:
with open("kontakter.txt","w") as file:
file.write("\n".join(kontakter.get(0,END)))
def ta_bort():
# Ta bort kontakter,genom att välja index av element och sparar värdet i variabel index.
index = kontakter.curselection()
print(index)
kontakter.delete(index)
def lägg_till():
# Ta inmatade värden från name,mobil och spara i kontakter.
# Använder .get() för att hämta
name = entry_1.get()
mobil = entry_2.get().replace(" ", "") # Använder replace för att rensa whitespace
# Varning när alla värden inte är ifyllda
if name == "" or mobil == "" :
label_error.config(text="Alla fälten är inte ifyllda")
else:
# trycka in dessa i kontakter med .insert() END för slutet av listan, dvs index "kan vara 0,1,2,3"
#Rensar error fältet innan man lägger till kontakten
label_error.config(text="")
kontakter.insert(END,name + " - " + mobil)
# Rensa fältet efter lägg till
entry_1.delete(0,END)
entry_2.delete(0,END)
kontakt = kontakter.get(0,END)
with open("kontakter.txt","w") as file:
file.write("\n".join(kontakt))
def uppdatera():
# Hämta det markerade data
index = kontakter.curselection()
name = entry_1.get()
mobil = entry_2.get()
# Varning när alla värden inte är ifyllda
if name == "" or mobil == "" :
label_error.config(text="Alla fälten är inte ifyllda")
else:
# trycka in dessa i kontakter med .insert() END för slutet av listan, dvs index "kan vara 0,1,2,3"
#Rensar error fältet innan man lägger till kontakten
label_error.config(text="")
# Raderar det ifyllda data
kontakter.delete(index)
#Skriver nytt
kontakter.insert(index,name + "-" + mobil)
entry_1.delete(0,END)
entry_2.delete(0,END)
# Skapar frame
#Namn
fram_1 = Frame(root)
fram_1.pack()
#Mobil
fram_2 = Frame(root)
fram_2.pack()
#Knappar
fram_3 = Frame(root)
fram_3.pack()
# Listbox
fram_4 = Frame(root)
fram_4.pack()
#Skapar label
#Namn
label_1 = Label(fram_1,text="Name:")
label_1.grid(row=0, column=0)
#Mobil
label_2 = Label(fram_2,text="Mobil:")
label_2.grid(row=1,column=0)
# Skapar entry
#namn
entry_1 = Entry(fram_1)
entry_1.grid(row=0,column=1)
#Mobil
entry_2 = Entry(fram_2)
entry_2.grid(row=1,column=2,)
# Kolla om filen finns, annars skapa den, behöver importera os.path
if not os.path.exists("kontakter.txt"):
open('kontakter.txt', 'w').close()
else:
pass
# Läsa från fil
data = []
with open("kontakter.txt" ,"r") as fil:
for line in fil:
data += [line]
# Listbox
kontakter = Listbox(fram_4,height=8,width=40,bg="pink")
kontakter.grid(row=0,column=0)
# Lägger till kontakter , första värdet är index följt av värde,
kontakter.insert(END,)
#Läsa in från fil
for i in range(len(data)):
kontakter.insert(i+0 , data[i])
# Error
label_error = Label(root,text="",fg="red")
label_error.pack()
# Knappar
# knapp Lägg till
button_1 = Button(fram_3,text="Lägg till",command=lägg_till)
button_1.grid(row=0,column=0)
# knapp edit
button_2 = Button(fram_3,text="Uppdatera",command=uppdatera)
button_2.grid(row=0,column=1)
# Knapp delete
button_3 = Button(fram_3,text="Radera",command=ta_bort)
button_3.grid(row=0,column=2)
# Knapp avsluta
button_4 = Button(fram_3,text="Avsluta",command=avsluta)
button_4.grid(row=0,column=3)
button_5 = Button(fram_3,text="Spara",command=spara)
button_5.grid(row=0,column=4)
root.attributes("-topmost", True)
root.mainloop()
Inside lägg_till() when you open the file use ab instead of w:
with open("kontakter.txt","ab") as file:
file.write("\n".join(kontakt))
By adding .strip() , I made workaround, but I think problem is still there.
# Läsa från fil
data = []
with open("kontakter.txt" ,"r") as fil:
for line in fil.readlines():
data += [line.strip()] #.strip() fix the problem
fil.close()
The problem in your program is kontakt = kontakter.get(0,END), which returns your data as follows :
('1 - 1\n', '2 - 2', '3 - 3')
Note that the third entry (3 - 3) is made after the GUI was closed once. By joining together with '\n'.join(), you get an additional space character:
'1 - 1\n\n2 - 2\n3 - 3\n'
I don't know the exact reason why this only happens if you close the program once.
You can avoid this conflict by using 'a' instead of 'w', which simply appends the string in the text file.
with open("kontakter.txt","a") as file:
file.write(name + " - " + mobil + '\n')

Cant get my functions (Munt2 and Munt1) to subtract my global variable (aantal_munten)

I have a problem with my code (trying to make the NIM game with a Tkinter GUI). Anyhow i cant get my functions (Munt1, Munt2) to subtract to my global (aantal_munten). And i dont know how to fix it. Can someone point me in the right direction? Also the TKinter gui is still a bit new for me so if you have any tips or tricks for me they are well appreciated!
import tkinter
import random
def toonStartscherm():
keuzescherm.pack_forget()
spelerscherm.pack_forget()
startscherm.pack()
def toonKeuzescherm():
keuzescherm.pack()
startscherm.pack_forget()
spelerscherm.pack_forget()
def spelOptie1():
keuzescherm.pack_forget()
startscherm.pack_forget()
spelerscherm.pack()
def randomSpeler():
beginnende_speler = random.choice(['1', '2'])
speler = beginnende_speler
if speler == '1':
speler = '2'
else:
speler = '1'
return str(speler)
def Munt1():
eenMunt = 1
aantal_munten -= eenMunt
def Munt2():
tweeMunt = 2
aantal_munten -= tweeMunt
nim_spel = tkinter.Tk()
global aantal_munten
aantal_munten = 7
startscherm = tkinter.Frame(master=nim_spel)
startscherm.pack()
start_welkom = tkinter.Label(startscherm, text= 'Welkom bij het NIM spel! \nHieronder volgende de spelregels.')
start_welkom.pack()
start_uitleg = tkinter.Label(startscherm, text= 'Het spel NIM start met 7 munten, elke speler mag één of twee munten pakken. \n De speler die de laatste munt pakt verliest!')
start_uitleg.pack() # zet uitleg automatisch in venster
doorgaan_knop = tkinter.Button(startscherm, text = 'Ik snap de regels!', fg = 'green', command = toonKeuzescherm) # maakt knop en laat stoppen
doorgaan_knop.pack(side = 'bottom')
keuzescherm = tkinter.Frame(master=nim_spel)
keuzescherm.pack()
keuze_opties = tkinter.Label(keuzescherm, text='Het NIM spel kan op twee manieren gespeeld worden. \n Optie 1: Tegen elkaar \n Optie 2: Tegen de computer')
keuze_opties.pack() # zet opties automatisch in venster
keuze_vraag = tkinter.Label(keuzescherm, text='Voor welke optie kies je?')
keuze_vraag.pack()
optie_1 = tkinter.Button(keuzescherm, text = 'Optie 1', fg = 'green', command = spelOptie1) # maakt knop en laat stoppen
optie_1.pack(side = 'left')
optie_2 = tkinter.Button(keuzescherm, text = 'Optie 2', fg = 'red', command = keuzescherm.quit) # maakt knop en laat stoppen
optie_2.pack(side = 'right')
spelerscherm = tkinter.Frame(master=nim_spel)
spelerscherm.pack()
beurt_speler = tkinter.Label(spelerscherm, text='Speler ' + (randomSpeler()) + ' is aan de beurt!')
beurt_speler.pack()
munten_over = tkinter.Label(spelerscherm, text='Er zijn nog ' + (str(aantal_munten)) + ' aantal munten over, hoeveel pak je er?')
munten_over.pack()
pak_1_munt = tkinter.Button(spelerscherm, text = '1 munt', fg = 'blue', command = Munt1)
pak_1_munt.pack(side = 'left')
pak_2_munt = tkinter.Button(spelerscherm, text = '2 munten', fg = 'blue', command = Munt2)
pak_2_munt.pack(side = 'right')
toonStartscherm()
nim_spel.mainloop()
def Munt1():
global aantal_munten
eenMunt = 1
aantal_munten -= eenMunt
def Munt2():
global aantal_munten
tweeMunt = 2
aantal_munten -= tweeMunt
I just added the global aantal_munten line and checked it, and it's working perfectly now.

correct way to implement thread python

I am implement a simple simulator of soccer with python using threads and lock, the app works fine but I have doubts in the way that implement the thread it seems to me that the first team has an advantage because is executing first.
def jugar(Equipo1, Equipo2):
# Busco las probabilidades de encajar por cada equipo
prob_encajar_eq1 = Equipo1.probabilidad_encajar()
prob_encajar_eq2 = Equipo2.probabilidad_encajar()
def jugar_equipo1(defensa_rival):
semaforo.acquire()
if Equipo1.hacer_pases():
Equipo1.shoot(defensa_rival)
semaforo.release()
def jugar_equipo2(defensa_rival):
semaforo.acquire()
if Equipo2.hacer_pases():
Equipo2.shoot(defensa_rival)
semaforo.release()
hilo_equipo1 = threading.Thread(name = 'hilo_eq1', target = jugar_equipo1, args = (prob_encajar_eq2,))
hilo_equipo2 = threading.Thread(name = 'hilo_eq2', target = jugar_equipo2, args = (prob_encajar_eq1,))
hilo_equipo1.start()
hilo_equipo2.start()
hilo_equipo1.join()
hilo_equipo2.join()
to make several attempts both teams, I do a cicle for a few seconds and inside the function jugar() which is the one that does the work with threads but here is were I have the doubts, because every time that jugar is executing the threads are declared again.
if __name__ == '__main__':
cargar_informacion()
eqA = Equipo(equipoA, ranking_eqA)
eqB = Equipo(equipoB, ranking_eqB)
probabilidades = porcenajes_ranking(ranking_eqA)
eqA.cargar_probabilidades(probabilidades)
probabilidades = porcenajes_ranking(ranking_eqB)
eqB.cargar_probabilidades(probabilidades)
starttime=time.time()
tiempo = 0
# creo la barra de progreso
bar = progressbar.ProgressBar(widgets=[
progressbar.Percentage(),
progressbar.Bar(),
], max_value=100).start()
# hacemos que el juego tarde aproximadamente 10seg en simularse.
while tiempo < 10:
time.sleep(0.3 - ((time.time() - starttime) % 0.3))
jugar(eqA,eqB)
tiempo = time.time() - starttime
bar += 2.8
bar.finish() # Para que finalice la barra de progreso
resultados_finales(eqA, eqB) # Mostramos el resultado final del partido.

Get variable from spinbox (Python)

finestra = Tk()
var = IntVar() #i did the same with the others variable except for the spin
cpu = Label(text="Seleziona la generazione del tuo processore:").pack()
core = Radiobutton(finestra,text="Core",value=1, variable=var)
core.pack()
x = Radiobutton(finestra,text="2 duo/ 2 quad",value=5/3, variable=var)
x.pack()
serie = Label(text="Seleziona il tuo processore:").pack()
i3 = Radiobutton(finestra,text="i3 xxxx/Pentium",value=51, variable=ivar)
i3.pack()
i5 = Radiobutton(finestra,text="i5 xxxx",value=65, variable=ivar)
i5.pack()
i7 = Radiobutton(finestra,text="i7 xxxx",value=75, variable=ivar)
i7.pack()
brand = Label(text="Seleziona la tua scheda video:").pack()
Radiobutton(finestra,text="GTX 1050", value=70,variable=gvar).pack()
Radiobutton(finestra,text="GTX 1050ti", value=75,variable=gvar).pack()
Label(text="Seleziona il numero di banchi di RAM e il loro quantitativo")
ram = Spinbox(finestra, from_=1, to=4).pack()
def callback(*args):
result.set(var.get()*ivar.get()+gvar.get()+ram.get())
var.trace("w", callback)
ivar.trace("w", callback)
gvar.trace("w",callback)
result = StringVar()
tdp = Label(textvariable=result).pack()
finestra.mainloop()
Well, I want that when I insert 1 or ... 4 in the spinbox, this value is summed with gvar and with the product of ivar and var.
I have also another question. In the 6th row there is a fraction, but when I run the program even though it doesn't give errors, it understand as if it were 5 (not 5/3). Can you explain me how can I use rational numbers?
PS: sorry for my italian-english
Fixed some things. ram = Spin....pack() does not return the spin object, but None. The 5/3 problem is that Python assumes integer division unless you put a decimal point on at least one of the arguments (5.0.3 works). This should get you going though.
from tkinter import *
finestra = Tk()
var = DoubleVar(value=5.0/3) #i did the same with the others variable except for the spin
ivar = IntVar(value=65)
gvar = IntVar(value=70)
spin = StringVar()
cpu = Label(text="Seleziona la generazione del tuo processore:").pack()
core = Radiobutton(finestra,text="Core",value=1, variable=var)
core.pack()
x = Radiobutton(finestra,text="2 duo/ 2 quad",value=5.0/3, variable=var)
x.pack()
serie = Label(text="Seleziona il tuo processore:").pack()
i3 = Radiobutton(finestra,text="i3 xxxx/Pentium",value=51, variable=ivar)
i3.pack()
i5 = Radiobutton(finestra,text="i5 xxxx",value=65, variable=ivar)
i5.pack()
i7 = Radiobutton(finestra,text="i7 xxxx",value=75, variable=ivar)
i7.pack()
brand = Label(text="Seleziona la tua scheda video:").pack()
Radiobutton(finestra,text="GTX 1050", value=70,variable=gvar).pack()
Radiobutton(finestra,text="GTX 1050ti", value=75,variable=gvar).pack()
Label(text="Seleziona il numero di banchi di RAM e il loro quantitativo")
ram = Spinbox(finestra, from_=1, to=4, textvariable=spin).pack()
def callback(*args):
result.set(var.get()*ivar.get()+gvar.get()+int(spin.get()))
var.trace("w", callback)
ivar.trace("w", callback)
gvar.trace("w",callback)
spin.trace("w", callback)
result = StringVar(value='none')
Label(textvariable=result).pack()
finestra.mainloop()

Categories