Tkinter entry boxes - python-3.x

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

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

How to edit information in tkinter

I'm trying to write a code to get the name, salary, and age and show it in a list. I want this code have the feature of deleteing and editing the information.
But in this step I don't know how delete or edit a particular information.
from tkinter import *
from tkinter import messagebox
from tkinter.ttk import *
i = 2
table_row = []
def getting():
global i
i = i + 1
data = []
var = IntVar()
c = Checkbutton(window, variable=var)
c.val = var
data.append(c)
c.grid(row=i, column=0)
value1=e11.get()
data.append(value1)
value2 = e22.get()
data.append(value2)
value3 = e33.get()
data.append(value3)
lblq = Label(window, text=data[1:])
lblq.grid(row=i, column=1)
table_row.append(data)
# print(table_row)
def delete_row():
for Noo, row in reversed(list(enumerate(table_row))):
if row[0].val.get() == 1:
for i in row:
i.destroy()
table_row(Noo)
window = Tk()
window.title("Table with add, edit and delete")
window.geometry('600x600')
def Closing():
res = messagebox.askokcancel("warning", "Are You sure!!!!!")
if res == True:
sys.exit()
############################################### #menu inside winodow
menu = Menu(window)
new_item = Menu(menu)
new_item.add_command(label="Exit", command=Closing)
menu.add_cascade(label='File', menu=new_item)
window.config(menu=menu)
###############################################
lblname =Label(window, text="Name")
lblname.place(x = 440,y = 130)
e11 = Entry(window, width=20)
e11.place(x = 440,y = 150)
lblsurname =Label(window, text="Salary")
lblsurname.place(x = 440,y = 180)
e22 = Entry(window, width=20)
e22.place(x = 440,y = 200)
lblage =Label(window, text="Age")
lblage.place(x = 440,y = 240)
e33 = Entry(window, width=20)
e33.place(x = 440,y = 260)
dl = Button(window, text='Delete',command=delete_row)
dl.place(x = 440,y = 10)
dl = Button(window, text='Edit')
dl.place(x = 440,y = 50)
B2 = Button(window, text="+ add emplyoee", command=getting)
B2.place(x = 440,y = 90)
v0 = StringVar()
e0 = Entry(window, textvariable=v0, state='readonly')
v0.set('Select')
e0.grid(row=1, column=0)
v1 = StringVar()
e1 = Entry(window, textvariable=v1, state='readonly')
v1.set('Information')
e1.grid(row=1, column=1)
window.mainloop()
Maybe I should use Class in my code, but I is difficult for me to use Class and tkinter simultaneously
You could use dictionary to keep single row - it would be more readable
When I add row I create dictionary with widgets and text from Entry, I add to list of rows and clear Entry.
If there is selected row in table then I don't create new row but replace text in selected row.
The same way I search selected row to copy text from row to Entry.
The same way I search selected row to remove row - destroy widgets and delete row on the list.
It is more easier to do it because I use dictionary to keep row and it is more readable.
from tkinter import *
from tkinter import messagebox
from tkinter.ttk import *
# --- functions ---
def closing():
res = messagebox.askokcancel("warning", "Are You sure!!!!!")
if res == True:
sys.exit()
def add_row():
global row_number
# check if there is selected row to update
update = None
for row in table_row:
if row['var'].get() == 1:
update = row
break # dont search next selected row
if update:
row['data'] = [e11.get(), e22.get(), e33.get()]
row['label']['text'] = row['data']
else:
row_number += 1
row = dict()
row['row_number'] = row_number
row['var'] = IntVar()
row['checkbutton'] = Checkbutton(window, variable=row['var'])
row['checkbutton'].grid(row=row_number, column=0)
row['data'] = [e11.get(), e22.get(), e33.get()]
row['label'] = Label(window, text=row['data'])
row['label'].grid(row=row_number, column=1)
table_row.append(row)
# clear entry
e11.delete('0', 'end')
e22.delete('0', 'end')
e33.delete('0', 'end')
lblnumber["text"] = "Row number: -"
def delete_row():
for row in reversed(table_row):
if row['var'].get() == 1:
# remove widgets
row['checkbutton'].destroy()
row['label'].destroy()
# remove row from list
del row
def edit_row():
for row in table_row:
if row['var'].get() == 1:
# remove all text
e11.delete('0', 'end')
e22.delete('0', 'end')
e33.delete('0', 'end')
# put text from row
e11.insert('end', row['data'][0])
e22.insert('end', row['data'][1])
e33.insert('end', row['data'][2])
lblnumber["text"] = "Row number: {}".format(row['row_number'])
break # dont search next selected row
# --- main ---
row_number = 2
table_row = []
window = Tk()
window.title("Table with add, edit and delete")
window.geometry('600x600')
menu = Menu(window)
new_item = Menu(menu)
new_item.add_command(label="Exit", command=closing)
menu.add_cascade(label='File', menu=new_item)
window.config(menu=menu)
lblnumber = Label(window, text="Row Number: -")
lblnumber.place(x=440, y=330)
e00 = Label(window, width=20)
e00.place(x=440, y=150)
lblname = Label(window, text="Name")
lblname.place(x=440, y=130)
e11 = Entry(window, width=20)
e11.place(x=440, y=150)
lblsurname = Label(window, text="Salary")
lblsurname.place(x=440, y=180)
e22 = Entry(window, width=20)
e22.place(x=440, y=200)
lblage = Label(window, text="Age")
lblage.place(x=440, y=240)
e33 = Entry(window, width=20)
e33.place(x=440, y=260)
dl = Button(window, text='Delete', command=delete_row)
dl.place(x=440, y=10)
dl = Button(window, text='Edit', command=edit_row)
dl.place(x=440, y=50)
B2 = Button(window, text="+ add emplyoee", command=add_row)
B2.place(x=440, y=90)
v0 = StringVar()
e0 = Entry(window, textvariable=v0, state='readonly')
v0.set('Select')
e0.grid(row=1, column=0)
v1 = StringVar()
e1 = Entry(window, textvariable=v1, state='readonly')
v1.set('Information')
e1.grid(row=1, column=1)
window.mainloop()

updating python3 tkinter label not working

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

After text widget opens, tkinter GUI crashes/does not respond whenever its closed

Right now, after I press the 'Time Range' button and call the calculateTime function, the text widget would appear with the results that I've inserted into it. However, after that, whenever I close the GUI window, the program would freeze and I'll have to forced quit it. This is my code:
import tkinter
from tkinter import *
import math
from tkinter import messagebox
class MyClass(tkinter.Frame):
def __init__(self, *args, **kwargs):
tkinter.Frame.__init__(self, *args, **kwargs)
#Setting up frame and widgets
vcmd1 = (self.register(self.__vcmd1), '%P', '%S')
vcmd2 = (self.register(self.__vcmd2), '%P')
vcmd3 = (self.register(self.__vcmd3), '%P', '%S')
label_iso = Label(self,text="Isotope A, Element")
label_vol = Label(self, text="Voltage")
label_range = Label(self, text="Charge Range")
label_iso.grid(row=0, column=0, sticky=E)
label_vol.grid(row=1, column=0, sticky=E)
label_range.grid(row=2, column=0, sticky=E)
self.entry1 = tkinter.Entry(self, validate="key", validatecommand=vcmd1)
self.entry2 = tkinter.Entry(self, validate="key", validatecommand=vcmd2)
self.entry3 = tkinter.Entry(self, validate="key", validatecommand=vcmd3)
self.entry1.grid(row=0, column=1)
self.entry2.grid(row=1, column=1)
self.entry3.grid(row=2, column=1)
def __vcmd1(self, P, S):
validString = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM,1234567890'
if not S in validString:
return False
if "," in P:
if (len(P) - 1) > len(P.replace(",","")):
return False
messagebox.showinfo("Error", "Expected Form: ex. 133,Cs")
else:
return True
def __vcmd2(self, P):
if P == '':
return True
try:
float(P)
return True
except ValueError:
messagebox.showinfo("Error", "Entry is not a float or integer")
return False
def __vcmd3(self, P, S):
if "," in P:
if len(P.split(",")) > 2:
return False
a = P.split(",")[0]
b = P.split(",")[1]
if a != '' and b != '':
try:
int(a)
int(b)
except ValueError:
messagebox.showinfo("Error", "Expected form: ex. 1,12")
return False
else:
return True
class TimeGenerator:
def __init__(self,master):
frame = MyClass(master)
frame.grid(columnspan=2)
button = Button(root, text='Time Range', command=self.calculateTime)
button.grid(row=3, columnspan=2)
self.text = Text(root)
self.iso = frame.entry1
self.vol = frame.entry2
self.r = frame.entry3
def calculateTime(self):
x = 5
if self.r.get() == "" or self.iso.get() == "" or self.vol.get() == "":
messagebox.showinfo("Error", "No field can be empty")
return None
self.iso = self.iso.get().replace(" ", "")
list = []
for e in self.iso.split(","):
list.append(e)
f = open("/Users/LazyLinh/PycharmProjects/mass.mas12.txt", "r")
i = 0
while (i < 40):
header = f.readline()
i += 1
self.mass = 0
#iterate through text file
for line in f:
line = line.strip()
columns = line.split()
if (list[0] == columns[3]):
if (list[1].lower() == columns[4].lower()):
if (len(columns) == 16):
self.mass = float(columns[13].replace("#","")) + float(columns[14].replace("#",""))
else:
self.mass = float(columns[12].replace("#","")) + float(columns[13].replace("#",""))
#Calculation
self.r = self.r.get().replace(" ", "")
tup = tuple(int(x) for x in self.r.split(","))
list = []
for q in range(tup[0], tup[1] + 1):
y = (x * math.sqrt(self.mass * 1.6605402e-27 / (2 * q * float(self.vol.get())))) * 10e6
list.append(y)
i = tup[0]
#inserting to text widget
for time in list:
self.text.insert("end", "%d: %s\n" % (i, time))
i = i + 1
self.text.pack()
root = Tk()
b = TimeGenerator(root)
root.mainloop()
I've tried to searched up on this topic, but I'm not really using any weird update() function, and text shows up after the function is finished, so how likely that it is an event loop problem? Am I also doing something wrong that could cause this problem?
Thank you!
You have widgets in the root window that use both pack and grid. You cannot do this. Within a given container (root window, frame, etc) you can use one or the other, but not both.
The reason your program freezes is due to pack and grid fighting to gain control of the layout. When you pack the text widget it causes a change in the size and/or position of other widgets in the root window. That triggers grid to try to re-layout the widgets it is responsible for. This triggers pack to try to re-layout the widgets it is responsible for, and on and on until the end of time.
My guess is that you need to use grid with self.text since you use grid everywhere else.

Resources