code is running good in main project , took some sample code from that as below
from tkinter import *
root = Tk()
root.geometry('200x200')
root.title('Testing')
num1 = StringVar()
num2 = StringVar()
def callback(integer):
if integer.isdigit():
return True
elif integer == "":
return True
else:
return False
def limit_no1(no):
c = no.get()[0:16]
no.set(c)
num1.trace("w", lambda name, index, mode, sv=num1: limit_no1(sv))
reg = root.register(callback)
ent1 = Entry(root, textvariable=num1)
ent1.pack()
ent1.config(validate="key", validatecommand=(reg, '%P'))
this has some condition as accepting only numbers and up 16 digits
but as like some web apps i need spacing after 4 characters
is there any method for that so that i can apply to this and and for input of currency also as ',' in btw data
I worked on some code but indexing getting issue in indexing
the below code continuation of above only
num2.trace("w", lambda name, index, mode, sv=num2: limit_no2(sv))
ent2 = Entry(root, textvariable=num2)
ent2.pack(pady=20)
ent2.config(validate="key", validatecommand=(reg, '%P'))
def limit_no2(no):
c = no.get()[0:19]
split_string = [c[i:i + 4] for i in range(0, len(c), 4)]
if len(split_string) > 1:
final_string = ''
for i in range(len(split_string)):
final_string += split_string[i]
final_string += " "
no.set(final_string)
else:
no.set(c)
root.mainloop()
Related
I've been coding a multiplication game where you can practice multiplications. I'm trying to add in a leaderboard using an external txt file that would sort by the highest percentage but have been stuck for quite a while now. It's able to append the new data and show the results. The txt file is laid out as name, age, score (Jackie Welles, 16, 70%)
from tkinter import *
import random
from tkinter import messagebox
class Timestable:
def __init__(self, parent):
Timestable.f1 = Frame(parent)
Timestable.f1.grid()
Timestable.f2 = Frame(parent)
Timestable.f2.grid()
Timestable.f2.grid_forget()
Timestable.f3 = Frame(parent)
Timestable.f3.grid()
Timestable.f3.grid_forget()
#frame 1 ========================================================
Label(self.f1,text="Multiplication Practice").grid()
Label(self.f1,text="Name:").grid()
Timestable.name = Entry (self.f1)
Timestable.name.grid()
Label(self.f1,text="Age").grid()
Timestable.age = Entry (self.f1)
Timestable.age.grid()
Timestable.incorrect=[]
Timestable.user = []
Timestable.checked1 = IntVar()
Timestable.checked2 = IntVar()
self.c1 = Checkbutton(self.f1, text='1',variable=Timestable.checked1,onvalue=1,offvalue=0,command=lambda:data.save(self))
self.c1.grid()
self.c2 = Checkbutton(self.f1, text='2', variable=Timestable.checked2,onvalue=1,offvalue=0,command=lambda:data.save(self))
self.c2.grid()
Timestable.w = Spinbox(self.f1, from_=1, to=5)
Timestable.w.grid()
Button(self.f1,text="Start", command=lambda: data.start(self)).grid()
#frame 2 ========================================================
Label(self.f2,text="Frame 2 ").grid()
self.x=0
self.correct=0
sub = lambda: data.Submit(self)
Button(self.f2,text="submit", command=sub).grid()
Timestable.entryWidget = Entry (self.f2)
Timestable.entryWidget.grid()
#frame 3 ========================================================
Label(self.f3,text="Frame 3 ").grid()
Timestable.congrats=Label(Timestable.f3,text="")
Timestable.congrats.grid()
Timestable.incdisplay = Label(Timestable.f3,text = Timestable.incorrect)
Timestable.incdisplay.grid()
Timestable.my_text=Text(self.f3,width=40,height=10)
Timestable.my_text.grid()
class data:
def openleader(self):
file=open('Leaderboard.txt',"a")
file.write(Timestable.name.get()+", "+Timestable.age.get()+", "+str(data.percent)+"%""\n")
file.close
file=open("Leaderboard.txt","r")
idk=file.readlines()
Timestable.my_text.insert(END,idk)
def save(self):
if Timestable.checked1.get() == 1:
Timestable.user.append(1)
if Timestable.checked2.get() == 1:
Timestable.user.append(2)
def clear_text(self):
Timestable.entryWidget.delete(0, 'end')
def Questions(self):
number1 = random.choice(Timestable.user)
number2 = random.randrange(1,12)
self.answer = number1 * number2
self.prompt = (str(number1) + " X " + str(number2))
quest = Label(Timestable.f2, text=self.prompt, width=len(self.prompt))
quest.grid()
return self.answer
def start(self):
Timestable.f1.grid_forget()
Timestable.f2.grid()
data.Questions(self)
def results(self):
Timestable.f2.grid_forget()
Timestable.f3.grid()
def Submit(self):
if Timestable.entryWidget.get() == "":
messagebox.showerror("Error", "Please enter a number.")
else:
if self.answer != int(Timestable.entryWidget.get().strip()):
messagebox.showinfo("Answer", "INCORRECT! Answer: " + str(self.answer))
Timestable.incorrect.append(self.prompt)
else:
messagebox.showinfo("Answer", "CORRECT!")
self.correct = self.correct +1
self.x=self.x+1
if self.x < int(Timestable.w.get()):
data.Questions(self)
data.clear_text(self)
else:
data.results(self)
data.percent = round(self.correct/self.x*100)
Timestable.congrats.configure(text="Congrats, you got "+ str(data.percent) +"% of the questions correct")
Timestable.incdisplay.configure(text=Timestable.incorrect)
data.openleader(self)
root = Tk()
root.geometry("300x300")
Timestable(root)
data()
root.mainloop()
That can be added fairly easily. We can also clean up the way it is diplayed as well. Since you are already essentially storing the data in csv format we can stick to that structure when presenting the output data.
def openleader(self):
file=open('Leaderboard.txt',"a")
file.write(Timestable.name.get()+", "+Timestable.age.get()+", "+str(data.percent)+"%""\n")
file.close
file=open("Leaderboard.txt","r").read()
headers = " ".join(["Name", "Age", "Score"])
output = [i.split(",") for i in file.split("\n") if i]
out_sort = sorted(output, key=lambda x: int(x[2][:-1]), reverse=True)
final = '\n'.join([headers, "-"*len(headers),*(" ".join(i) for i in out_sort)])
Timestable.my_text.insert(END, final)
I'm new to programming and I'm trying to make an app that calculates the smallest common for you, but for some reason whenever i run it, tkinter seems to just freeze and i don't know what the error seems to be. I suspect that it's the myLabel part, since I can still read the result inside the Terminal.
Thanks in advance~
from tkinter import *
root = Tk()
root.title("I can find the smallest common, unless you enter letters... I'm dyslexic.")
numbers_list = []
global numbers
numbers = Entry(root, width = 10, borderwidth = 5, state = DISABLED)
numbers.pack()
numbers.insert(0, "")
#
def button_click():
#each gets a button
get_smallest_common = Button(root, text = 'Confirm your number!'
, command = smallest_common)
get_smallest_common.pack()
get_smallest_common = Button(root, text = 'Undo!'
, command = lambda: undo())
get_smallest_common.pack()
get_smallest_common = Button(root, text = 'Start the search!'
, command = lambda: find_the_s_common())
get_smallest_common.pack()
#disable the start button
def switch():
myButton['state'] = DISABLED
#configure helps bringing a disabled thing back to normal state
numbers.configure(state = "normal")
def smallest_common():
#add to the list for late use
numbers_list.append(numbers.get())
print(numbers_list)
numbers.delete(0, END)
def undo():
#add to the list for late use
numbers_list.pop()
print(numbers_list)
numbers.delete(0, END)
def find_the_s_common():
process_list = []
condition = True
x = 0
while condition:
#the multiplication keep rising till count is 3
a = int(x) + 1
x = a
#loop to multiply the number with x + 1
for number in numbers_list:
y = int(number) * int(a)
process_list.append(y)
#check whether the result has been added to append into list
if y in process_list:
#check whether the list contains two duplicates to
if process_list.count(y) == 3:
condition = False
result = 'The number is ' + str(y) + '!'
print(result)
else:
continue
else:
continue
myLabel = Label(root, text = result)
myLabel.pack()
#combine the two function for myButton
def button_click_switch():
button_click()
switch()
myButton = Button(root, text = 'Click me to start'
, command = lambda: [button_click(), switch()])
myButton.pack()
root.mainloop()
Most probably, you have problem if the numbers entered is less than 3. As a result, one simple way is to decrease the condition to 2 and if a single number is entered the result is the number itself, if 2 or more no freezing.
NOTE: Freezing here is actually, while loop is running as condition is always True, because of process_list.count(y) == 3 will always be False if less than 3 number entered.
See my suggestion:
from tkinter import *
root = Tk()
root.title("I can find the smallest common, unless you enter letters... I'm dyslexic.")
numbers_list = []
global numbers
numbers = Entry(root, width = 10, borderwidth = 5, state = DISABLED)
numbers.pack()
numbers.insert(0, "")
#
def button_click():
#each gets a button
get_smallest_common = Button(root, text = 'Confirm your number!', command = smallest_common)
get_smallest_common.pack()
get_smallest_common = Button(root, text = 'Undo!', command = lambda: undo())
get_smallest_common.pack()
get_smallest_common = Button(root, text = 'Start the search!' , command = lambda: find_the_s_common())
get_smallest_common.pack()
#disable the start button
def switch():
myButton['state'] = DISABLED
#configure helps bringing a disabled thing back to normal state
numbers.configure(state = "normal")
def smallest_common():
#add to the list for late use
numbers_list.append(numbers.get())
print(numbers_list)
numbers.delete(0, END)
def undo():
#add to the list for late use
numbers_list.pop()
print(numbers_list)
numbers.delete(0, END)
def find_the_s_common():
process_list = []
condition = True
x = 0
if len(numbers_list) == 1: # RETURN IF THE LIST HAS A SINGLE VALUE
result = 'The number is ' + str(numbers_list[0]) + '!'
else:
while condition:
#the multiplication keep rising till count is 3
a = int(x) + 1
x = a
#loop to multiply the number with x + 1
for number in numbers_list:
y = int(number) * int(a)
process_list.append(y)
#check whether the result has been added to append into list
if y in process_list:
#check whether the list contains two duplicates to
if process_list.count(y) == 2: # DECREASE THE CONDITIONS TO 2
condition = False
result = 'The number is ' + str(y) + '!'
print(result)
else:
continue
else:
continue
myLabel = Label(root, text = result)
myLabel.pack()
#combine the two function for myButton
def button_click_switch():
button_click()
switch()
myButton = Button(root, text = 'Click me to start', command = lambda: [button_click(), switch()])
myButton.pack()
root.mainloop()
Suggestion to add two conditons;
(1) create a condition until at least 1 number is entered! if len(numbers_list) == 0, loop to enter a number.
(2) create a condition, until N number is added, let's say user must enter at least 3 numbers, change process_list.count(y) == 3 to process_list.count(y) == N and add condition if len(numbers_list) != N, loop to enter more numbers.
I have a project, that currently will only ask 1 question and then break, giving me the message:
IndexError: list index out of range
the error is on line 42 which is:
label.config(text=question[q]).
Here is the code:
from tkinter import *
import tkinter as tk
q = -1
count = 0
correct = 0
incorrect = 0
question=["File compression software is an example of.. software", "Each piece of hardware e.g printer, monitor, keyboard, will need an up to date... installed", "application softwares control the computer, true or false?"]
answer = ["utility", "driver", "false"]
answer_cap = ["Utility","Driver","False"]
root = Tk()
name = tk.Label(root,text = "Computing quiz")
name.pack()
label = tk.Label(root,text = question[0])
label.pack()
entry = tk.Entry(root)
entry.pack()
def out():
global q,correct,incorrect,count
while count < len(question):
ans = entry.get()
if answer[q] == ans or answer_cap[q] == ans :
q+=1
entry.delete(0, END)
correct+=1
print(correct)
label.config(text=question[q])
else:
q+=1
entry.delete(0, END)
incorrect+=1
print(incorrect)
label.config(text=question[q])
entry.delete(0, END)
label.config(text = "Correct: "+str(correct) + " Incorrect: "+str(incorrect))
print(correct)
def stop():
global q,correct,incorrect
q = 0
correct = 0
incorrect = 0
entry.delete(0, END)
label.config(text = question[0])
button = tk.Button(root,text = "Submit",command = out)
button.pack()
button_two = tk.Button(root,text = "Restart",command = stop)
button_two.pack()
Look at your while loop. You are doing something while count < ..., but inside the loop count is not updated, but q is. Because of this q will be very very big soon, so it will be much higher then the len(question). No wonder the IndexError
You have to correct that loop, because even if you deal with the IndexError the while loop will run forever.
A workaround (I do not suggest this, in my opinion you should just correct the whole while loop) could be to except the IndexError and break out of the loop
I'm trying to make a program that stores a user's recipe, using a tkinter gui to do so. I need to make a way to keep track of what is inputted, and store it in a text file. I have tried using lists to no avail, and think that using a string is the way forward, but have run into a problem - each time I try to add to the string, it over writes and doesn't keep the data from before. I have tried to use
mystring.join(a + b + etc)
but that didnt work, and my new code is as follows:
from tkinter import *
number_people = 1
itemslist = ''
itemslist1 = ''
def script (): # Puts main body of program into a function so that it can be re-run #
global number_people
number_people = 1
global itemslist, itemslist1
itemslist = ''
itemslist1 = ''
#### MAIN ####
fake_window = Tk() # #
new_recipe_window = fake_window # Opens window, allows it be closed #
start_window = fake_window # #
start_window.title("Recipe Book Task") # #
#### MAIN ####
### Functions ###
def close (x):
global start_window
global new_recipe_window
(x).withdraw()
def moreitems ():
a = item_box.get()
b = quantity_units_box.get()
c = len(a)
if a == '':
pass
elif b == '':
pass
else:
item_box.delete(0,c)
quantity_units_box.delete(0,c)
global itemslist
global itemslist1
itemslist1 = itemslist + a + ', ' + b + ', '
print ("Items list =", itemslist1)
def new_recipe ():
new_recipe_window = Tk()
new_recipe_window.title("New Recipe")
close(start_window)
recipe_name_label = Label(new_recipe_window, text="Recipe Name: ")
recipe_name_label.grid(row=0, column=0)
recipe_name_box = Entry(new_recipe_window)
recipe_name_box.grid(row=0, column=1)
def continue_1 ():
global check_box
check_box = recipe_name_box.get()
if check_box == '':
pass
else:
global itemslist
global itemslist1
itemslist1 = itemslist + check_box + ', '
print (itemslist1)
continue_button_1.destroy()
item_label = Label(new_recipe_window, text="Ingredient: ")
item_label.grid(row=1, column=0)
global item_box
item_box = Entry(new_recipe_window)
item_box.grid(row=1, column=1)
quantity_units_label = Label(new_recipe_window, text="Quantity and Units: ")
quantity_units_label.grid(row=2, column=0)
global quantity_units_box
quantity_units_box = Entry(new_recipe_window)
quantity_units_box.grid(row=2, column=1)
def continue_2 ():
check_box_1 = item_box.get()
check_box_2 = quantity_units_box.get()
if check_box_1 == '':
pass
elif check_box_2 == '':
pass
else:
global itemslist
itemslist.join(check_box_1)
itemslist.join(check_box_2)
continue_button_2.destroy()
more_items.destroy()
add_people_label = Label(new_recipe_window, text="Choose amount of people")
add_people_label.grid(row=3, column=0, columnspan=2)
def add ():
global number_people
number_people += 1
num_people_label.config(text="Number of people: " + str(number_people))
def minus ():
global number_people
if number_people > 1:
number_people -= 1
num_people_label.config(text="Number of people: " + str(number_people))
def finish ():
itemslist.join(str(number_people))
print("ItemsList = " + itemslist)
saveFile = open("Recipe_Book.txt", "a")
saveFile.write(itemslist + '\n')
saveFile.close
close(new_recipe_window)
script()
num_people_label = Label(new_recipe_window, text="Number of people: " + str(number_people))
num_people_label.grid(row=4, column=0, columnspan=2)
add_people_button = Button(new_recipe_window, text="+")
add_people_button.grid(row=5, column=1)
add_people_button.config(command=add)
minus_people_button = Button(new_recipe_window, text="-")
minus_people_button.grid(row=5, column=0)
minus_people_button.config(command=minus)
finish_button = Button(new_recipe_window, text="Finish")
finish_button.grid(row=6, column=0, columnspan=2)
finish_button.config(command=finish)
continue_button_2 = Button(new_recipe_window, text="Continue...")
continue_button_2.grid(row=3, column=0)
continue_button_2.config(command=continue_2)
more_items = Button(new_recipe_window, text="Add another item", command=moreitems)
more_items.grid(row=3, column=1)
continue_button_1 = Button(new_recipe_window, text="Continue...")
continue_button_1.grid(row=1, column=0)
continue_button_1.config(command=continue_1)
new_recipe = Button(start_window, text="New Recipe", command=new_recipe)
new_recipe.grid(row=0, column=0)
script()
So to recap, my question is how do I keep the string itemslist and itemslist1 from being overwritten, or is there another way I can do this?
EDIT FOR AAAANTOINE
I was about to clarify for you what I wanted, but I just figured out what I was doing wrong, thanks for your help, you taught me what .join does, thanks.
Your code never actually assigns to itemslist other than at the beginning of script(). The only time it ever appears on the left side of the assignment operator is when it's being initialized.
You can probably change all instances of itemslist1 to itemslist and have a working program.
Edit
On further review, I suspect that you think str.join(v) appends string v to the str. That's not how join works.
>>> s = 'something'
>>> s.join('a')
'a'
join takes a list as an argument and joins its contents together, with the str instance as a separator. Typically, the source string would actually be an empty string or a comma.
>>> s.join(['a', 'b', 'c'])
'asomethingbsomethingc'
>>> ','.join(['a', 'b', 'c']) # comma separation
'a,b,c'
>>> '-'.join(s) # spell it out!
's-o-m-e-t-h-i-n-g'
How do I do it, then?
You append to strings using this syntax:
>>> s = s + 'a'
>>> s
'somethinga'
(Or the shorthand version:)
>>> s += 'a'
>>> s
'somethinga'
Ok, so I am definitely new to Python so please bear with my ignorance.
I am writing a practice interactive function with PyCharm.
Basically, I want to generate an interactive window with two text input fields and two buttons.
One button (QUIT) will quit the app, and the other one (Run DNA Scan) starts it.
The first text input field takes a DNA sequence (ex: atgcagatgac) and the other one takes a smaller 'search' sequence (ex: cag).
The plan is that once the two text fields are filled in, pressing the 'Run DNA Sequence' will start the DNA_scan() function - which I wrote and works fine when called on its own.
The problem is, the 'QUIT' button works the way it should, but the 'Run DNA Sequence' button does nothing.
Thanks in advance!
Here is my code as I have it now:
import tkinter
from tkinter import *
class Application(Frame):
def DNA_scan(self): #this is a search function I wrote myself - it works fine on its own
dataf = str(input())
s = str(input())
datar = dataf[::-1]
print('Your data input contains ' + str((dataf.count(s))) + ' instances of your search input on the FORWARD strand:')
data = dataf.lower()
b = s.lower()
c = b.upper()
print(data.replace(b,c))
datar = datar.lower()
i = 0
reverse = ''
s = s.lower()
for ch in datar:
if ch == 'a':
ch = 't'
reverse = reverse + ch
i = i+1
elif ch == 't':
ch = 'a'
i = i+1
reverse = reverse + ch
elif ch == 'c':
ch = 'g'
i = i+1
reverse = reverse + ch
elif ch == 'g':
ch = 'c'
i = i+1
reverse = reverse + ch
print('And, your data input contains ' + str((reverse.count(s))) + ' instances of your search input on the REVERSE strand:')
a = reverse.lower()
b = s.lower()
c = b.upper()
print(a.replace(b,c))
def createWidgets(self):
root.title("DNA scan")
Label (text="Please enter your DNA sequence:").pack(side=TOP,padx=10,pady=10)
dataf = Entry(root, width=10).pack(side=TOP,padx=10,pady=10)
Label (text="Please enter your search sequence:").pack(side=TOP,padx=10,pady=10)
s = Entry(root, width=10).pack(side=TOP,padx=10,pady=10)
self.button = Button(root,text="Run DNA scan",command=self.DNA_scan)
self.button.pack()
self.QUIT = Button(self)
self.QUIT["text"] = "QUIT"
self.QUIT["fg"] = "red"
self.QUIT["command"] = self.quit
self.QUIT.pack({"side": "left"})
def __init__(self, master=None):
Frame.__init__(self, master)
self.filename = None
self.pack()
self.createWidgets()
root = Tk()
root.title("DiNA")
root.quit()
app = Application(master=root)
app.mainloop()