I am doing a coding where I need to program different math flashcards and the user has to answer them. But when answering them, the message keeps saying the same number and not updating the new numbers that it is supposed to get.
from tkinter import messagebox
from random import randint
def clicked():
messagebox.showinfo('Rules of the Game', '1. You are going to be provided with basic arithmetic (Adding, Subtracting, Multiplying)'
'\n2. You are going to answer them'
'\n3. Based on the answer you gave, it will keep track of the correct and incorrect answers including how many in total you have answered')
root = Tk()
root.title('Math Flash Cards')
root.geometry('900x500')
Title = Label(root, text="Title", font=('Arial', 30))
Title.grid(row = 0, column = 4)
Rule_btn = Button(root, text="Click Here for Rules", font=('Arial'), command=clicked)
Rule_btn.grid(row = 3, column = 4)
#Create random flashcard numbers
def math_random():
global nums
number_1 = randint(1,10)
number_2 = randint(1,10)
add_1.configure(text = number_1)
add_2.configure(text = number_2)
def answer_add():
answers = number_1 + number_2
if int(add_ans.get()) == answers:
response = 'Correct ' + str(number_1) + ' + ' + str(number_2) + ' = ' + str(answers)
elif int(add_ans.get()) != answers:
response = 'Wrong! ' + str(number_1) + ' - ' + str(number_2) + ' = ' + str(answers)
answer_message.config(text = response)
add_ans.delete(0, 'end')
math_random()
global nums
number_1 = randint(1,10)
number_2 = randint(1,10)
global add_1
global add_2
add_1 = Label(root, text='+', font=('Arial', 20))
add_2 = Label(root, text='+', font=('Arial', 20))
math_operator = Label(root, text='+', font=('Arial', 20))
add_1.grid(row = 5, column = 3)
math_operator.grid(row = 5, column = 4)
add_2.grid(row = 5, column = 5)
add_1.configure(text = number_1)
add_2.configure(text = number_2)
global add_ans
add_ans = Entry(root, font = ('Arial', 14))
add_ans.grid(row = 7, column = 4)
add_ans_btn = Button(root, text ='Click', font = ('Arial'), command= answer_add)
add_ans_btn.grid(row = 7, column = 5)
global answer_message
answer_message = Label(root, text='Type you answer with the provided space above', font=('Arial'))
answer_message.grid(row = 10, column = 4)
What should I do to make it update? I kept making changes to the code, but it is not changing when the numbers are changing.
Related
Newbie here, I am working on a small Python project and it requires to accept a numerical input from user and upon a button click it should insert that number of rows - entry boxes - for further input collection. Is it possible to do it in a loop and how? I tried it in a loop but is inserting only first row.
label_6.place(x=0,y=320)
total_participants = tk.Entry(root, width="5", textvariable=StringVar())
total_participants.place(x=150,y=320)
def action():
num_participants = int(total_participants.get())
coordinate = 400
first_name_label = Label(root, text="First Name",width=20,font=("bold", 11))
first_name_label.place(x=0,y=coordinate)
second_name_label = Label(root, text="Second Name",width=20,font=("bold", 11))
second_name_label.place(x=150,y=coordinate)
email_label = Label(root, text="Email ID",width=20,font=("bold", 11))
email_label.place(x=300, y =coordinate )
first_name = []
second_name = []
email_id = []
for i in range(1, num_participants + 1):
fn[i] = Entry(root, width="15").place(x=40,y=coordinate + 40)
sn[i] = Entry(root, width="15").place(x=190,y=coordinate + 40)
em[i] = Entry(root, width="40").place(x=340,y=coordinate + 40)
label_8 = Button(root, text="Participants Details",font=("bold", 13), command = participant_details)
label_8.place(x=30,y=360)
Im making my own cypher encryption and I want to put the result into the entry field called output. Now im just using print() so I could test if I got a result. But that was only for testing. This is one of the first times I used Python so if there are some other things I could have done better please let me know :)
this is what I have so far.
from tkinter import *
#Make frame
root = Tk()
root.geometry("500x300")
root.title("Encryption Tool")
top_frame = Frame(root)
bottom_frame = Frame(root)
top_frame.pack()
bottom_frame.pack()
#Text
headline = Label(top_frame, text="Encryption Tool", fg='black')
headline.config(font=('Courier', 27))
headline.grid(padx=10, pady=10)
Key = Label(bottom_frame, text="Key:", fg='black')
Key.config(font=('Courier', 20))
Key.grid(row=1)
Text_entry = Label(bottom_frame, text="Text:", fg='black')
Text_entry.config(font=('Courier', 20))
Text_entry.grid(row=2)
Output_text = Label(bottom_frame, text="Output:", fg='black')
Output_text.config(font=('Courier', 20))
Output_text.grid(row=3)
Key_entry = Entry(bottom_frame)
Key_entry.grid(row=1, column=1)
Text_entry = Entry(bottom_frame)
Text_entry.grid(row=2, column=1)
Output_text = Entry(bottom_frame)
Output_text.grid(row=3, column=1)
#Encryption_button
def encrypt():
result = ''
text = ''
key = Key_entry.get()
text = Text_entry.get()
formule = int(key)
for i in range(0, len(text)):
result = result + chr(ord(text[i]) + formule + i * i)
result = ''
Encryption_button = Button(bottom_frame, text="Encrypt", fg='black')
Encryption_button.config(height = 2, width = 15)
Encryption_button.grid(row = 4, column = 0, sticky = S)
Encryption_button['command'] = encrypt
#Decryption_button
def decrypt():
result = ''
text = ''
key = Key_entry.get()
text = Text_entry.get()
formule = int(key)
for i in range(0, len(text)):
result = result + chr(ord(text[i]) - formule - i * i)
print(result)
result = ''
Decryption_button = Button(bottom_frame, text="Decrypt", fg="black")
Decryption_button.config(height = 2, width = 15)
Decryption_button.grid(row = 5, column = 0, sticky = S)
Decryption_button['command'] = decrypt
#Quit_button
def end():
exit()
Quit_button = Button(bottom_frame, text="Quit", fg='black')
Quit_button.config(height = 2, width = 15)
Quit_button.grid(row = 6, column = 0, sticky = S)
Quit_button['command'] = end
root.mainloop()
The most common way to do this with tkinter would be with a StringVar() object you can connect to the Entry object (Some documentation here).
output_entry_value = StringVar()
Output_text = Entry(bottom_frame, textvariable=output_entry_value)
Output_text.grid(row=3, column=1)
then you can .set() the result in the stringvar, and it will update in the entries you connected it to:
output_entry_value.set(result)
I've a Tkinter-programm where I regularly (10 times/second) update Labels with certain sensor-values.
The problem is that they are arranged with .grid right next to each other and when a value gets/loses a place (e.g. 10 -> 9, 60 -> 150, you see the number needs extra space) the label jumps back and forth (because the number gains or loses a space and therefore .grid responds by adjusting the Label).
How can i avoid that? Do I need to change Text & Numbers to a certain font or is there a function that fixes the Labels place? I'd be happy about useful answers.
Here's a code example (please notice how the labels are adjusting cause that's the problem):
#!/usr/bin/env
import sys
import time
import subprocess
from Tkinter import *
import numpy
import random
i = 0
x = 0
def GetValue():
x = random.randint(0,10000)
time.sleep(0.1)
return x
def UebergabeTkinter():
while 1:
CompleteValue = GetValue()
Variable1.set(CompleteValue)
Variable2.set(CompleteValue)
Variable3.set(CompleteValue)
Variable4.set(CompleteValue)
root.update()
def Exit():
root.destroy()
return
try:
root = Tk()
Leiste = Menu(root)
root.config(menu = Leiste)
DateiMenu = Menu(Leiste)
Leiste.add_cascade(label = "datei", menu = DateiMenu)
DateiMenu.add_command(label = "Exit", command = Exit)
EditMenu = Menu(Leiste)
Leiste.add_cascade(label = "edit", menu = EditMenu)
Variable1 = IntVar()
Variable2 = IntVar()
Variable3 = IntVar()
Variable4 = IntVar()
Ausgang = 0
for column in range(0,8,2):
String1 = "Ausgang "
String1 += `Ausgang`
Ausgang = Ausgang + 1
Label(text = String1).grid(row=0,column=column)
Ausgang = 0
for column in range(0,8,2):
String1 = "Der Wert von "
String2 = " ist: "
String1 += `Ausgang`
Ausgang = Ausgang + 1
String3 = String1+String2
Label(text = String3).grid(row=2,column=column)
Label1 = Label(root, textvariable = Variable1)
Label1.grid(row = 2, column = 1, sticky = W+E+N+S)
Label2 = Label(root, textvariable = Variable2)
Label2.grid(row = 2, column = 3, sticky = W+E+N+S)
Label3 = Label(root, textvariable = Variable3)
Label3.grid(row = 2, column = 5, sticky = W+E+N+S)
Label4 = Label(root, textvariable = Variable4)
Label4.grid(row = 2, column = 7, sticky = W+E+N+S)
UebergabeTkinter()
root.mainloop()
except KeyboardInterrupt:
print "Hallo"
You can give labels a fixed width:
Label1 = Label(root, textvariable=Variable1, width=4)
Just make sure they are large enough to fit every number that could be put in, since of course next no the label not shrinking when the number is shorter, this also means that they will not grow to fit larger numbers.
I'm new to python so this code is a mess but I have found a bug I can't fix. The program is meant to give you maths sums to solve and I was using buttons that sent an int as a value from 1 to 4 then that is tested in the guess function to generate the next question. The problem is that the int is not changing when the buttons are pressed and every sum is an addition one because it is set as 1 in the root. If anyone could help that would be great, thanks in advance!
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from random import randint
def plus(*args):
op = 1
def minus(*args):
op = 2
def times(*args):
op = 3
def divide(*args):
op = 4
def guess(*args):
try:
numberguess = int(ans.get())
except ValueError:
ask.set('That is not a number!')
global number
gdif = number - numberguess
if gdif == 0:
ask.set('You got it right!')
global score
sco = score.get() + 1
score.set(sco)
result = messagebox.askquestion('', 'Next question')
if result == 'yes':
if top.get() == 0:
noone = randint(1,10)
notwo = randint (1,10)
else:
noone = randint(1,top.get())
notwo = randint(1,top.get())
ans_entry.focus()
if op == 1:
number = noone + notwo
numb.set('What is ' + str(noone) + ' + '+ str(notwo) + '?')
elif op == 2:
number = noone - notwo
numb.set('What is ' + str(noone) + ' - '+ str(notwo) + '?')
elif op == 3:
number = noone * notwo
numb.set('What is ' + str(noone) + ' x '+ str(notwo) + '?')
elif op == 4:
number = noone / notwo
numb.set('What is ' + str(noone) + ' / '+ str(notwo) + '?')
elif result == 'no':
root.destroy()
elif gdif>0:
ask.set(ans.get() + ' is too low')
elif gdif<0:
ask.set(ans.get() + ' is too high')
ans.set('')
root = Tk()
root.title('Maths Game') #window title
mainframe = ttk.Frame(root, padding = '3 3 12 12')
mainframe.grid(column = 0, row = 0, sticky = (N, W, E, S))
mainframe.columnconfigure(0,weight = 1)
mainframe.rowconfigure(0, weight = 1)
#organises grid well
ans = StringVar()
numb = StringVar()
ask = StringVar()
pts = StringVar()
score = IntVar()
top = IntVar()
#sets as variables
ans_entry = ttk.Entry(mainframe, width = 7, textvariable = ans) #defines guess entry
ans_entry.grid(column = 2, row = 1, sticky = (W, E)) #places guess entry on grid
ttk.Label(mainframe, textvariable = numb).grid(column = 2, row = 2, sticky = (W, E)) #label
ttk.Label(mainframe, textvariable = ask).grid(column = 3, row = 1, sticky = (W, E)) #label
ttk.Label(mainframe, textvariable = score).grid(column = 3, row = 2, sticky = (E)) #label
ttk.Label(mainframe, textvariable = pts).grid(column = 4, row = 2, sticky = (W, E))
ttk.Button(mainframe, text = 'Answer', command = guess).grid(column = 3, row = 3, sticky = (W, E)) #guess button
top_entry = ttk.Entry(mainframe, width = 3, textvariable = top)
top_entry.grid(column = 3, row = 4, sticky = (E))
ttk.Button(mainframe, text = '+', command = plus).grid(column = 1, row = 5, sticky = (W, E))
ttk.Button(mainframe, text = '-', command = minus).grid(column = 2, row = 5, sticky = (W, E))
ttk.Button(mainframe, text = 'x', command = times).grid(column = 3, row = 5, sticky = (W, E))
ttk.Button(mainframe, text = '/', command = divide).grid(column = 4, row = 5, sticky = (W, E))
for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5) #pads grid nicely
ans_entry.focus() #cursor starts in box
root.bind('<Return>', guess) #binds entry key to guess button
noone = randint(1,10)
notwo = randint (1,10)
number = noone + notwo
numb.set('What is ' + str(noone) + ' + '+ str(notwo) + '?')
right = False
sco = 0
score.set(sco)
pts.set(' points')
one = 10
op = 1
root.mainloop() #launches main code
Because op is a local variable in every function.
You should add global op:
def plus(*args):
global op
op = 1
.
.
.
But be aware that this is a very sub-optimal way of doing it.
It makes much more sense to have a class, then have these functions as its methods. That way they will all have access to the op variable without it having to be a global.
I am making a maths test using tkinter. I have 4 entries to allow the user to input the answers of questions. the answers must be in integer format if not it will give a long error. I wanted my program to check if the inputted value is an integer or not.and then if it is not an integer open up a message box telling the user to check the answers.
here is my code: (it's a long code because I didn't know how to shorten it, I'm not a programmer)
from tkinter import*
from tkinter import messagebox
from random import*
n1= randint(1,6)
n2= randint(1,9)
ques1 = n1, "x", n2, "="
c1= n1*n2
n1= randint(8,15)
n2= randint(1,7)
ques2 = n1, "-", n2, "="
c2= n1-n2
n1= randint(1,10)
n2= randint(5,15)
ques3 = n1, "+", n2, "="
c3= n1+n2
n1= randint(5,12)
n2= randint(1,10)
ques4 = n1, "x", n2, "="
c4= n1*n2
#window
window = Tk()
window.geometry("280x450")
window.title("quiz")
window.configure(background='yellow')
def checkthrough():
if ans1.get() == '':
messagebox.showinfo("error", "check again ")
elif ans2.get() == '':
messagebox.showinfo("error", "check again ")
elif ans3.get() == '':
messagebox.showinfo("error", "check again ")
elif ans4.get() == '':
messagebox.showinfo("error", "check again ")
else:
save()
#this is where i tried to check if it's an integer or not
try:
ans1 == int()
except:
messagebox.showinfo("error", "check again ")
def save():
score = 0
if c1==int(ans1.get()):
score= score + 1
if c2==int(ans2.get()):
score = score+1
if c3==int(ans3.get()):
score = score+1
if c4==int(ans4.get()):
score = score+1
fscore.set(score)
def savetofile():
result = result ="\n "+ namestudent.get() + " " + fscore.get()+"/4"
messagebox.showinfo("results", "your results been saved successfuly")
if int(year.get())==1:
f = open('results C1.txt', 'a')
f.write(result)
f.close()
if int(year.get())==2:
f = open('results C2.txt', 'a')
f.write(result)
f.close()
if int(year.get())==3:
f = open('results C3.txt', 'a')
f.write(result)
f.close()
#frame
frame = Frame(window)
frame.columnconfigure(0, weight=1)
frame.rowconfigure(0, weight=1)
#variables
namestudent = StringVar()
ans1 = StringVar()
ans2 = StringVar()
ans3 = StringVar()
ans4 = StringVar()
fscore = StringVar()
year = StringVar()
#labels
name = Label(window, text = "type your name:")
name.grid(row= 6, column = 0)
yr = Label(window, text = "type your class:")
yr.grid(row= 7, column = 0)
q1 = Label(window,text = ques1, height = 3, bg = 'yellow')
q1.grid(row = 1,column=0)
q2 = Label(window,text = ques2, height = 3, bg = 'yellow')
q2.grid(row = 2,column=0)
q3 = Label(window,text = ques3, height = 3, bg = 'yellow')
q3.grid(row = 3,column=0)
q4 = Label(window,text = ques4, height = 3, bg = 'yellow')
q4.grid(row = 4,column=0)
#entrys
name_entry= Entry(window, textvariable= namestudent)
name_entry.grid(row = 6, column=1)
yr_entry= Entry(window, textvariable= year)
yr_entry.grid(row = 7, column=1)
q1_entry = Entry(window, width = 6, textvariable = ans1)
q1_entry.grid(row = 1,column=1)
q2_entry = Entry(window, width = 6, textvariable = ans2)
q2_entry.grid(row = 2,column=1)
q3_entry = Entry(window, width = 6, textvariable = ans3)
q3_entry.grid(row = 3,column=1)
q4_entry = Entry(window, width = 6, textvariable = ans4)
q4_entry.grid(row = 4,column=1)
#buttons
finish = Button(window, width = 5, text = "finish",command= checkthrough)
finish.grid(row = 5,column=0)
finalS_label = Label(window, textvariable=fscore)
finalS_label.grid(row=5, column=1)
saving = Button(window, width = 5, text = "save", command= savetofile)
saving.grid(row= 8, column=0)
window.mainloop()
I read some other post about the same question and I tried to use their answers in my code but still I'm getting the same error.
thanks.
In order to check if a string is integer-convertible, just try converting it and check for exceptions.
try:
integer_result = int(string_result)
except ValueError:
print("not a valid integer")
else:
print("value is", integer_result)
To do this in your case, you want to extract the values from ans1 &c. beforehand, then pass the raw strings to int().