Python Tkinter, can I limit the number of entry? - python-3.x

How can I limit the number of user inputs such that if the user has wrongly tried 5 times already, the system will end immediately?
I have tried to use While loop as usual to achieve. However, the while loop seems to be unable to calculate the number of incorrect input.
Please let me know what should I do. Appreciate
import tkinter as tk
import csv
from tkinter import messagebox
def user_login():
locals()
entry_user_name = entry_usr_name.get()
entry_user_pwd = entry_usr_pwd.get()
with open(r'user.csv', 'r') as user_file
reader = csv.reader(user_file)
user = list(reader)
found = False
count1 = 5
for count in range(len(user)):
if entry_user_name == user[count][0]:
if entry_user_pwd == user[count][1]:
target = count
found = True
break
else: found = False
else: found = False
count1 -= 1
if not found:
tk.messagebox.showerror(title='Error',
message='Invalid password. Please enter again. You have '+str(count1)+ ' left')
if count1 == 0:
tk.messagebox.showerror(title='Error',
line1='Too many input. The system will be ended immediately',
line2='This will be recorded in the security system')
if found:
tk.messagebox.showinfo(title='Successful login',
message='Valid password.')
startpage()
window = tk.Tk()
entry_username = tk.Entry(window, font='Courier 17')
entry_pwd = tk.Entry(window,font='Courier 17')
entry_usr_name.place(x=330, y=245)
entry_usr_pwd.place(x=330, y=345)
login_button= tk.Button(window,
command=user_login) # with some setting
login_button.place(x=440, y=420)
window.mainloop()

You can use a tracking variable to keep record of how many attempts a person has made.
Here is a simple example.
import tkinter as tk
root = tk.Tk()
counter = 1 # tracking variable
tk.Label(root, text="User Name: ").grid(row=0, column=0)
tk.Label(root, text="Password: ").grid(row=1, column=0)
entry_name = tk.Entry(root)
entry_pass = tk.Entry(root)
entry_name.grid(row=0, column=1)
entry_pass.grid(row=1, column=1)
def check_login():
global counter, entry_name, entry_pass
x = entry_name.get()
y = entry_pass.get()
if counter <= 5: # if counter 5 or less then check login info
if x == "Bob" and y == "mypassword":
print("Correct!")
else:
counter += 1 # add 1 to counter
print("Bad login! Please try again")
else:
print("Exceeded max attempt.")
tk.Button(root, text="Login", command=check_login).grid(row=2, column=0, columnspan=2)
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()

How to get Int value from spinbox to create new entries

I created a simple spin box. what I want is, as I increase or
decrease the value in spin box, a new entry should be created or
deleted respectively.
I am not able to get the Int value from the spinbox.
I tried, user_input = int(sb.get()), But this also didn't work.
I am getting this error,
'str' object cannot be interpreted as an integer.
,,,
1st code:
from tkinter import *
root = Tk()
sb_var = IntVar()
sb = Spinbox(root, bg='gray', textvariable=sb_var)
sb.pack()
user_input = sb.get()
for x in range(user_input):
my_entry = Entry(root)
my_entry.pack()
root.mainloop()
,,,
2nd code:
from tkinter import *
root = Tk()
root.geometry("500x400")
def up_or_down(direction):
if direction == "up":
my_entry = Entry(root)
my_entry.pack()
if direction == "down": # I don't know how to code this condition
my_entry.destroy()
tcl_up_or_down = root.register(up_or_down)
sb = Spinbox(root, from_=0, to=100, bg='gray', command=(tcl_up_or_down, '%d'))
sb.pack()
root.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()

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.

Tkinter freezing - threads? Progressbar?

I wrote some code that creates progressbars that update when a json file is changed (by a different program). The idea is that this code will be combined with a much larger project to give the user information about the json file as it is being written.
My Problem: If I activate one of the progressbars, the entire GUI freezes. That progressbar will work just fine but I can't start any of the others.
My Plan: I've read up on tkinter and python and I believe that what I want is for each progressbar to operate on a different thread. I tried that; but it's still freezing. And the Quit button won't work properly either. Any suggestions? Or an easier way to approach this??
Here is my code (sorry for the length):
import threading
import time
from Tkinter import *
import json
import Queue
from time import sleep
master = Tk()
#somewhere accessible to both:
callback_queue = Queue.Queue()
#see (thread_working.py) for debugging help
######ProgressBar Code (my_progressbar.py)
class Meter(Frame):
#make a progress bar widget
def __init__(self, master, fillcolor = 'darkblue', text='', value=0.0, **kw):
Frame.__init__(self, master, bg='lightgray', width=350, height=20)
self.configure(**kw)
self._c = Canvas(self, bg=self['bg'], width=self['width'], height=self['height'], highlightthickness=0, relief='flat', bd=0)
self._c.pack(fill='x', expand=1)
self._r = self._c.create_rectangle(0,0,0, int(self['height']), fill=fillcolor, width=0)
self._t = self._c.create_text(int(self['width'])/2, int(self['height'])/2, text='')
self.set(value)
def set(self, value=0.0):
text = str(int(round(100 * value))) + ' %'
self._c.coords(self._r, 0, 0, int(self['width']) * value,int(self['height']))
self._c.itemconfigure(self._t, text=text)
self.update()
progbarlock = False # start with the prograssbar marked as not occupied
class guibuild:
def __init__(self):
guibuild.progbarlock = False
self.progbar = Meter(theframe) #makes the progressbar object
self.progbar.set(0.0) #sets the initial value to 0
self.progbar.pack(side=LEFT)
self.mybutton = Button(theframe, text="My Button", command = self.interval).pack(side = LEFT)
def stop_progbar(self):
self.progbar.stop()
def interval(self):
if guibuild.progbarlock == False:
counter = 0
#sleep(5) #slow down the loop
guibuild.progbarlock = True
i = float(0) #i is going to be the value set on the progressbar
while i <= 1.0: #will stop at 100%
the_file = open("sample.json")
data = json.load(the_file)
curr = data["curr_line"]
total = data["total_lines"]
if counter == total:
print "stop" #for debug purposes
self.stop_progbar
#pass
elif curr == counter:
#print "curr = counter" #debug
pass
elif curr == counter+1:
i += 1.0/total
#print i #debug
self.progbar.set(i) #apply the new value of i to the progressbar
print "the progressbar should reflect", str(int(round(i*100))) +"%progress right now"
print "the counter will increase"
counter += 1
#print counter #debug purposes
self.stop_progbar
#print "test"
else:
print "something is wrong - running.json is not available"
time.sleep(5)
guibuild.progbarlock = False
##########################################################################################################
def create_bar():
guibuild()
######Make the actual GUI
#master = Tk()
global theframe #makes the frame object global
theframe = Frame(master)
theframe.pack()
frame2 = Frame(master)
frame2.pack(side=BOTTOM)
quitbutton = Button(frame2, text="Quit", fg = "darkred", command = master.quit).pack(side=LEFT)
#original command was theframe.quit, original location was theframe (vs master)
##############Threading Stuff#####################
beginbutton = Button(theframe, text="Make Bar", command =create_bar).pack(side = BOTTOM)
def my_thread(func_to_call_from_main_thread):
callback_queue.put(guibuild)
#this must be here and below
def from_main_thread_nonblocking():
while True:
try:
callback = callback_queue.get(True) #doesn't block #was false
except Queue.Empty: #raised when queue is empty
break
callback()
#this allows for it to be activated several times
threading.Thread(target=guibuild).start()
while True:
master.mainloop()
master.destroy()
from_main_thread_nonblocking()
master.destroy()
sample.json looks like this:
{
"curr_line": 1,
"total_lines": 5
}
Edit: I got this fixed but found a new bug. Will post the corrected code once the bug is fixed in case anyone comes looking for an answer and finds this.
I fixed all of the bugs and want to share this answer for any future searchers. As #BryanOakley said, Tkinter does not work with threads. I researched some more and decided to delete all of my while loops and make use of the Tkinter after() method. Below is the modified part of my code.
class guibuild:
def __init__(self):
self.master = master
guibuild.progbarlock = False
self.progbar = Meter(theframe) #makes the progressbar object
self.progbar.set(0.0) #sets the initial value to 0
self.progbar.pack(side=LEFT)
self.counter = 0
self.i = float(0) #i is the value set to the progressbar
self.mybutton = Button(theframe, text="My Button", command = self.interval).pack(side = LEFT)
def stop_progbar(self):
self.progbar.stop()
def interval(self):
if guibuild.progbarlock == False:
guibuild.progbarlock = True
the_file = open("sample_running.json")
data = json.load(the_file)
curr = data["curr_line"]
command = data["curr_line_text"]
total = data["total_lines"]
print self.counter
if self.i == 1.0:
self.stop_progbar
print "100% - process is done"
self.master.after_cancel(self.interval)
elif self.counter == total:
print "stop" #for debug purposes
self.i = 1.0
self.master.after(5000, self.interval)
elif curr == self.counter:
print self.counter
print self.i
self.master.after(5000, self.interval)
elif curr == self.counter+1:
self.i += 1.0/total
print self.i #debug
self.progbar.set(self.i) #apply the new value of i to the progressbar
print "the progressbar should reflect", str(int(round(self.i*100))) +"%progress right now"
print "the counter will increase"
self.counter += 1
print self.counter #debug purposes
self.stop_progbar
self.master.after(5000, self.interval)
else:
print "something is wrong - running.json is not available"
self.master.after(5000, self.interval)
guibuild.progbarlock = False
Note that the call for self.master.after() needs to occur after every if statement - this is so that self.master.after_cancel() works when it is invoked. Cheers!

Resources