updating python3 tkinter label not working - python-3.x

I can manually update label and entry if i clicked the manual button, but if i clicked the auto button... the console show the random number but the widgets are not updating.
from tkinter import *
import random
import time
def manual_settxt():
for t in range(0,3):
rd = random.randrange(1,100)
labelWidgets[t].configure(text=rd)
entryWidgets[t].delete(0,END)
entryWidgets[t].insert(0,rd)
def auto_settxt():
while True:
time.sleep(3)
for t in range(0,3):
rd = random.randrange(1,100)
print(rd)
labelWidgets[t].configure(text=rd)
entryWidgets[t].delete(0,END)
entryWidgets[t].insert(0,rd)
root = Tk()
namesInput = [1,2,3]
entryWidgets = []
labelWidgets = []
for i in range(0, len(namesInput)):
labelWidgets.append(Label(root,text=namesInput[i],justify='center'))
entryWidgets.append(Entry(root,width=5,justify='center'))
labelWidgets[-1].grid(row=i+1,column=0)
entryWidgets[-1].grid(row=i+1,column=1)
b1 = Button(root, text = "Manual", command=manual_settxt)
b1.grid(row=4,column=0)
b2 = Button(root, text = "Auto", command=auto_settxt)
b2.grid(row=4,column=1)
root.mainloop()

You created an infinite loop. Delete while True.
I refactored some code: used Thread for non-blocking functionality.
Try this
from tkinter import *
import random
import time
from threading import Thread
def manual_settxt():
for index in range(3):
rd = random.randrange(1,100)
labelWidgets[index].configure(text=rd)
entryWidgets[index].delete(0,END)
entryWidgets[index].insert(0,rd)
def job():
for index in range(3):
time.sleep(1)
rd = random.randrange(1,100)
print(rd)
labelWidgets[index].configure(text=rd)
entryWidgets[index].delete(0,END)
entryWidgets[index].insert(0,rd)
def auto_settxt():
Thread(target=job).start()
root = Tk()
namesInput = [1,2,3]
entryWidgets = []
labelWidgets = []
for index, name in enumerate(namesInput):
labelWidgets.append(Label(root, text=name, justify='center'))
entryWidgets.append(Entry(root, width=5, justify='center'))
labelWidgets[-1].grid(row=index+1,column=0)
entryWidgets[-1].grid(row=index+1,column=1)
b1 = Button(root, text = "Manual", command=manual_settxt)
b1.grid(row=4,column=0)
b2 = Button(root, text = "Auto", command=auto_settxt)
b2.grid(row=4,column=1)
root.mainloop()

I use "root.after" and the script seems to be working fine.
from tkinter import *
import random
import time
def manual_settxt():
for index in range(3):
rd = random.randrange(1,100)
labelWidgets[index].configure(text=rd)
entryWidgets[index].delete(0,END)
entryWidgets[index].insert(0,rd)
def auto_settxt():
for index in range(3):
rd = random.randrange(1,100)
print(rd)
labelWidgets[index].configure(text=rd)
entryWidgets[index].delete(0,END)
entryWidgets[index].insert(0,rd)
root.after(1000, auto_settxt)
root = Tk()
namesInput = [1,2,3]
entryWidgets = []
labelWidgets = []
for index, name in enumerate(namesInput):
labelWidgets.append(Label(root, text=name, justify='center'))
entryWidgets.append(Entry(root, width=5, justify='center'))
labelWidgets[-1].grid(row=index+1,column=0)
entryWidgets[-1].grid(row=index+1,column=1)
b1 = Button(root, text = "Manual", command=manual_settxt)
b1.grid(row=4,column=0)
b2 = Button(root, text = "Auto", command=auto_settxt)
b2.grid(row=4,column=1)
root.after(1000, auto_settxt)
root.mainloop()

Related

Multiprocessing code in a game isn't working

My problem is that when I do a multiprocessing code it isn't working for a script I wrote.
The code I am writing is for a clicker game by the way.
Here's the code I tried. What I was hopping it would do was to open a Tk window, which it does, but the part that's wrong is every 0.6 seconds 1 is added to score, but that isn't happening. The part that isn't working is the def autopoints and bellow that
from tkinter import *
import time
import multiprocessing
root = Tk()
c = Canvas(root, width=100, height=100)
score = 0
PointsPerClick = 10
PriceForUpgrade = 100
pointsfromautogen = 1
timeforautogen = 0.6
priceforautogen = 500
pricefortimeautogen = 2000
root.title("Clicker Game")
#this is basically the code for the text in the window
scoretext = StringVar()
scoretext.set(score)
score_label = Label(root, textvariable = scoretext)
upgradecosttext = StringVar()
upgradecosttext.set(PriceForUpgrade + 10)
upgradecost_label = Label(root, textvariable = upgradecosttext)
pointsperclicktext = StringVar()
pointsperclicktext.set(PointsPerClick)
pointsperclicktext_label = Label(root, textvariable = pointsperclicktext)
pointsfromautogentext = StringVar()
pointsfromautogentext.set(pointsfromautogen)
pointsfromautogentext_label = Label(root, textvariable = pointsfromautogentext)
#code for the buttons
def bAaction():
global score
score += PointsPerClick
scoretext.set(score)
def bBaction():
global score
global PriceForUpgrade
if score > PriceForUpgrade:
global PointsPerClick
score -= PriceForUpgrade
PointsPerClick += 5
PriceForUpgrade += 150
upgradecosttext.set(PriceForUpgrade + 1)
pointsperclicktext.set(PointsPerClick)
else:
print('Not enough. Need more score')
def bCaction():
global pointsfromautogen
global priceforautogen
if score > priceforautogen:
pointsfromautogen += 10
pointsfromautogentext.set(priceforautogen + 1)
priceforautogen += 100
#code for the auto generator (aka the part that isn't working)
def autopoints():
time.sleep(0.1)
score + pointsfromautogen
scoretext.set(score)
if __name__ == '__main__':
ap = multiprocessing.Process(target=autopoints)
ap.start()
ap.join()
def bDaction():
if score < pricefortimeautogen:
if timeforautogen > 0.5:
timeforautogen - 0.1
pricefortimeautogen + 2000
else:
print('At max level or not enough points')
#all of the buttons
buttonA = Button(root, text='Points Generator', command=bAaction)
buttonB = Button(root, text='Upgrade', command=bBaction)
buttonC = Button(root, text ='Auto Points Upgrade', command=bCaction)
buttonD = Button(root, text='Speed Up Auto Points', command=bDaction)
#just packing everything needed
buttonA.pack()
buttonB.pack()
buttonC.pack()
buttonD.pack()
score_label.pack()
upgradecost_label.pack()
pointsperclicktext_label.pack()
pointsfromautogentext_label.pack()
c.pack()
root.mainloop()

python how to select printer for print receipt

the following code is working successfully, i need to print receipts. i want to select printer to print receipts. in this code how can i add printer function. I need to printer selecting option separately.
i don't know which function using in this code.
i hope you will help for this,
Thanks im advance.
from tkinter import ttk
import tkinter as tk
from tkinter import*
def update():
listBox.insert('','end',value=('APL', t1.get(),t2.get(),t3.get()))
listBox.insert('','end',value=('cPL', t4.get(),t5.get(),t6.get()))
def update():
if t1.get() == '' or t2.get() == '' or t3.get() == '':
pass
else:
listBox.insert('','end',value=('APL', t1.get(),t2.get(),t3.get()))
listBox.insert('','end',value=('cPL', t4.get(),t5.get(),t6.get()))
total = 0.0
try:
for child in listBox.get_children():
total += float(listBox.item(child, 'values')[3])
totText.set(total)
except:
pass
lbl = Label(root,text=total,font=('helvetica',21))
lbl.grid(row=5)
def print():
tott = float(totText.get())
top = Toplevel()
top.geometry("300x300")
top.config(bg="white")
l = Label(top, text='-------RECEIPT-------')
l.pack()
l.config(bg="white")
heading = Label(top, text='\tItem\tPRICE\tQTY\tTotal')
heading.pack()
heading.config(bg="white")
for child in listBox.get_children():
item = (listBox.item(child, 'values')[0])
price = float(listBox.item(child, 'values')[1])
qty = float(listBox.item(child, 'values')[2])
tot = float(listBox.item(child, 'values')[3])
item1 = Label(top, text=f'{item}\t{price}\t{qty}\t{tot}')
item1.config(bg="white")
item1.pack()
tot = Label(top, text=f'Total\t{tott}')
tot.config(bg="white")
tot.pack()
root = tk.Tk()
root.geometry('1000x600')
e8 = tk.Label(root,text="APL").grid(row=1,column=0)
t1 = tk.Entry(root)
t1.grid(row=1,column=1)
t2 = tk.Entry(root)
t2.grid(row=1,column=2)
t3 = tk.Entry(root)
t3.grid(row=1,column=3)
e9 = tk.Label(root,text="cPL").grid(row=2,column=0)
t4 = tk.Entry(root)
t4.grid(row=2,column=1)
t5 = tk.Entry(root)
t5.grid(row=2,column=2)
t6 = tk.Entry(root)
t6.grid(row=2,column=3)
global totText
totText = StringVar()
cols = ('Item', 'PRICE', 'QTY', 'Total')
listBox = ttk.Treeview(root, columns=cols, show='headings')
for col in cols:
listBox.heading(col, text=col)
listBox.grid(row=1, column=0, columnspan=2)
listBox.place(x=10, y=300)
b = tk.Button(root,text='Update Listbox',command=update)
b.grid(row=3)
Button(root, text="print", command=print, height=3, width=13).place(x=850, y=120)
root.mainloop()

AttributeError: 'users_Arduino' object has no attribute 'Progressbar'

I have tried in several ways, set it with ttk.Progressbar, with self.progresso.Progressbar ... and nothing, anyone can help? I'm still young then sorry for ignorance. If they can be as clear as possible, thank you.
from tkinter import *
from tkinter import ttk
import time
class users_Arduino:
def __init__(self,window):
self.wind = window
self.wind.title("System F2T - Cadastro Arduino")
menubar = Menu(window)
arduino = Menu(menubar,tearoff=0)
menubar.add_cascade(label = "Arduino",menu=arduino)
arduino.add_command(label = "Conectar/Inserir dados-BD", command=self.getSerialData)
window.config(menu = menubar)
def bar():
progress['value'] = 20
root.update_idletasks()
time.sleep(1)
progress['value'] = 40
root.update_idletasks()
time.sleep(1)
progress['value'] = 50
root.update_idletasks()
time.sleep(1)
progress['value'] = 60
root.update_idletasks()
time.sleep(1)
progress['value'] = 80
root.update_idletasks()
time.sleep(1)
progress['value'] = 100
def getSerialData(self):
self.progresso = Toplevel()
self.progresso.title("System F2T - Progress")
self.progresso.geometry("290x200")
#self.progresso["bg"] = "#000"
progress = self.Progressbar(self.progresso,orient = HORIZONTAL, length = 100, mode = 'determinate').pack(pady = 10)
Button(self.progresso, text = 'Start', command = self.bar).pack(pady = 10)
if __name__ == '__main__':
window = Tk()
window['bg'] = "#000"
users_Arduino(window)
window.mainloop()
You are trying to access a class attribute by using self.Progressbar, which obviously won't work. What you intended is to create a Progressbar, which should be done like below:
progress = ttk.Progressbar(self.progresso,orient = HORIZONTAL, length = 100, mode = 'determinate').pack(pady = 10)
Next, you wanted the Progressbar to update every second until it reaches 100, but calling time.sleep will block your main thread and freeze your GUI. You need to use root.after method.
Also if you call something=widget(...).pack() at the same line, you are not keeping a proper reference of the object. The return value will just be None.
So everything wrapped up:
from tkinter import *
from tkinter import ttk
class UsersArduino:
def __init__(self,window):
self.wind = window
self.wind.title("System F2T - Cadastro Arduino")
self.value = 0
menubar = Menu(window)
arduino = Menu(menubar,tearoff=0)
menubar.add_cascade(label = "Arduino",menu=arduino)
arduino.add_command(label = "Conectar/Inserir dados-BD", command=self.getSerialData)
window.config(menu = menubar)
def bar(self):
self.progress['value'] +=20
if self.progress['value'] <=100:
self.wind.after(1000,self.bar)
def getSerialData(self):
self.progresso = Toplevel()
self.progresso.title("System F2T - Progress")
self.progresso.geometry("290x200")
self.progress = ttk.Progressbar(self.progresso,orient = HORIZONTAL, length = 100, mode = 'determinate')
self.progress.pack(pady = 10)
Button(self.progresso, text = 'Start', command = self.bar).pack(pady = 10)
if __name__ == '__main__':
window = Tk()
window['bg'] = "#000"
UsersArduino(window)
window.mainloop()

Tkinter entry boxes

I need to count from a starting input value to an ending value using tkinter entry boxes but the 2 output files are blank except for brackets and I know that the csv outputs work it's just getting the user input that is the issue. Thanks for any help.
There is the current code.
import csv
from tkinter import *
# Variables/Arrays
oddArray = []
evenArray = []
def main():
for i in range(oute1, oute2):
x = i
# Odds
if(x % 2 == 1):
oddArray.append(x)
# Evens
elif(x % 2 == 0):
evenArray.append(x)
with open("odd_labels", "w") as outputFile1:
writer1 = csv.writer(outputFile1)
writer1.writerow([oddArray])
with open("even_labels", "w") as outputFile2:
writer2 = csv.writer(outputFile2)
writer2.writerow([evenArray])
# gui framework
myGui = Tk()
# myGui.geometry('225x50')
# myGui.title("Label Creator")
Label(myGui, text="Starting value: ").grid(row=0)
Label(myGui, text="Ending value: ").grid(row=1)
a = IntVar()
b = IntVar()
e1 = Entry(myGui, textvariable=a).grid(row=0, column=1)
e2 = Entry(myGui, textvariable=b).grid(row=1, column=1)
oute1 = a.get()
oute2 = b.get()
Button(myGui, text="Start", command=main).grid(row=3)
myGui.mainloop()
The problem is how you create your entry fields.
When you use the grid manager at the end of a widget creation then you are unable to use .get() on it because the grid manager is returning None. To avoid this you need to make sure you create your widget first then define where it goes on a separate line.
Change:
e1 = Entry(myGui, textvariable=a).grid(row=0, column=1)
e2 = Entry(myGui, textvariable=b).grid(row=1, column=1)
to:
e1 = Entry(myGui, textvariable=a)
e1.grid(row=0, column=1)
e2 = Entry(myGui, textvariable=b)
e2.grid(row=1, column=1)
I notived your oute1 and oute2 are both only created on the start of the program. You need to move them into a function and it should work fine in your main function.
Try this:
import csv
from tkinter import *
myGui = Tk()
oddArray = []
evenArray = []
Label(myGui, text="Starting value: ").grid(row=0)
Label(myGui, text="Ending value: ").grid(row=1)
a = IntVar()
b = IntVar()
e1 = Entry(myGui, textvariable=a)
e1.grid(row=0, column=1)
e2 = Entry(myGui, textvariable=b)
e2.grid(row=1, column=1)
def main():
oute1 = a.get()
oute2 = b.get()
for i in range(oute1, oute2):
x = i
# Odds
if(x % 2 == 1):
oddArray.append(x)
# Evens
elif(x % 2 == 0):
evenArray.append(x)
with open("odd_labels", "w") as outputFile1:
writer1 = csv.writer(outputFile1)
writer1.writerow([oddArray])
with open("even_labels", "w") as outputFile2:
writer2 = csv.writer(outputFile2)
writer2.writerow([evenArray])
Button(myGui, text="Start", command=main).grid(row=3)
myGui.mainloop()

Need help switch labels when button pressed in tkInter

I need it so that when I press the button it will switch between 2 labels, when I have managed to create a second statement now I need to be able to switch between the two. I have no clue what to do to get this to work, please help
def changeLabelText():
z = True
print(z)
if z == True:
print("The current text is", l1['text'])
z = False
return z
elif z == False:
print("The current text is", l12['text'])
z = True
return z
l1['text'] = "Changed Text"
l12['text'] = "Text"
b1 = Button(app, text="Change Text", command=changeLabelText)
l1 = Label(app, text="Text")
l12 = Label(app, text="New Text")
It's unclear for what reason you're using those redundant conditions, but here's a small example how you can switch labels (technically - a text options as your function's name claims):
try:
import tkinter as tk
except ImportError:
import Tkinter as tk
def changeLabelText():
l1['text'], l2['text'] = l2['text'], l1['text']
app = tk.Tk()
b1 = tk.Button(app, text="Change Text", command=changeLabelText)
l1 = tk.Label(app, text="Text")
l2 = tk.Label(app, text="New Text")
l1.pack()
l2.pack()
b1.pack()
app.mainloop()

Resources