I am trying to get an int from entry - python

import tkinter as tk
import math
window = tk.Tk()
label = tk.Label(text = 'Want to find a root?')
label.pack()
entry = tk.Entry(fg = 'blue')
entry.pack()
n = entry.get()
number = int(n)
answers = {}
roots = [x for x in range(2, 100)]
def search(number):
for i in roots:
if number > i:
if number//i**2 != 0:
if number//i**2 != 1:
if (i**2)*(number//i**2) == number:
answers[i] = number//i**2
print(answers)
search(number)
window.mainloop()
So I need to get a integer from entry and work with it as a int, but entry gives me a string with which i can't work.I can't type a int in entry because the programm doesn't start due to an error
Error:number = int(n)
ValueError: invalid literal for int() with base 10: ''

You are getting the value of an Entry you created seconds ago. Of course it will be nothing! Use entry.get() when you need it, not anytime before. Put the .get() in the search function, and then call int on it.
Updated search function:
def search(number):
number = int(entry.get())
for i in roots:
if number > i:
if number//i**2 != 0:
if number//i**2 != 1:
if (i**2)*(number//i**2) == number:
answers[i] = number//i**2
And remove the two lines in your code that get the entry value and turn it into an int.

Related

First numbers stuck together and horizontal in the label (tkinter)

im makin a machine for prime number,But I want the output of the numbers to be stuck together and horizontal, for example:
>>2,3,5,7,11,13,......
but machine do this:
It is neither horizontal nor joined together
my code:
from tkinter import *
def prime():
a = int(spin.get())
for number in range(a + 1):
if number > 1:
for i in range(2,number):
if (number % i) == 0:
break
else:
Label(app,text=number,).pack()
app = Tk()
app.maxsize(300,300)
app.minsize(300,300)
spin = Entry(app,font=20)
spin.pack()
Button(app,text="prime numbers",command=prime).pack()
app.mainloop()
You can do this by storing the numbers in a list (result) and then joining them at the end.
def prime():
a = int(spin.get())
result = []
for number in range(a + 1):
if number > 1:
for i in range(2,number):
if (number % i) == 0:
break
else:
result.append(str(number))
Label(app, text = ",".join(result)).pack()
The numbers have to be stored as strings so join will work.
Edit
To wrap every 10 numbers, add the following in place of Label(app, ...) after the for loop:
for i in range(0, len(result), 10):
Label(app, text = ",".join(result[i:i+10])).pack()

enter special character in between text in python at after certain length

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

ValueError: invalid literal for int() with base 10: '' (Tkinter)

When I try to run this code, a ValueError appears alluding to the function numRandom. I though Python could pass a string representation of a int to an int.
import tkinter
import random
window = tkinter.Tk()
window.geometry('600x500')
x = random.randint(1,300)
remainingTime = True
Attempts = 4
def numRamdom():
global Attempts
while Attempts > 0:
numWritten = int(entryWriteNumber.get())
if numWritten > x:
lblClue.configure(text = 'Its a bigger number')
Attempts = Attempts -1
if numWritten < x:
lblClue.configure(text = 'Its a smaller number')
Attempts = Attempts -1
if numWritten == x:
lblClue.configure(text = 'Congratulations ;)')
remainingTime = False
return remainingTime, countdown(0)
if Attempts == 0:
remainingTime = False
return remainingTime, countdown(0), Attempts, gameOver()
entryWriteNumber = tkinter.Entry(window)
entryWriteNumber.grid(column = 0, row = 1, padx = 10, pady = 10)
numRamdom()
window.mainloop()
The problem is because when the code is ran, it directly calls numRamdom(), that is, initially the entry widgets are empty, and they run it with those empty entry widget and hence the error. So just assign a button and a command, like:
b = tkinter.Button(root,text='Click me',command=numRamdom)
b.grid(row=1,column=0)
Make sure to say this before the mainloop() after the def numRamdom():. The button just runs the function only when the button is clicked.
Or if you want button-less then try:
METHOD-1:
root.after(5000,numRamdom) #after 5 sec it will execute function
But keep in mind, if the user doesn't enter properly in 5 sec then some error would pop up.
METHOD-2:
def numRamdom(event):
......
entryWriteNumber.bind('<Return>',numRamdom)
This is so that, if you press enter key in the entry widget(after entering data) it will run the function.
Hope this helps, do let me know if any errors.
Cheers
Here's a fully working example based on your code. Your problem was trying to convert the contents of the Entry before anything was inside of it. To fix this problem, you can add a button which calls the command numRamdom()
import tkinter
import random
window = tkinter.Tk()
window.geometry('600x500')
x = random.randint(1,300)
remainingTime = True
Attempts = 4
def numRamdom():
global Attempts, lblClue, x
if Attempts > 0:
numWritten = int(entryWriteNumber.get())
if numWritten < x:
lblClue.configure(text = 'Its a bigger number')
Attempts = Attempts -1
elif numWritten > x:
lblClue.configure(text = 'Its a smaller number')
Attempts = Attempts -1
else:
lblClue.configure(text = 'Congratulations ;)')
remainingTime = False
#return remainingTime, countdown(0)
if Attempts == 0:
remainingTime = False
#return remainingTime, countdown(0), Attempts, gameOver()
else:
lblClue.configure(text = "You ran out of attempts!")
entryWriteNumber = tkinter.Entry(window)
entryWriteNumber.grid(column = 0, row = 1, padx = 10, pady = 10)
entryWriteButton = tkinter.Button(window, text = "Push me!", command = numRamdom)
entryWriteButton.grid(column = 1, row = 1)
lblClue = tkinter.Label(window)
lblClue.grid(row = 2, column = 1)
window.mainloop()
You'll still get an error if the value passed is not able to be converted into an integer, but that's easy to fix with an if statement.

How to fix StringVar.get() issue

I am trying to make autocomplete GUI (like Google's) in Tkinter using StringVar. I defined a callback function , where i used StringVar.get(), where I for different input in Entry I get different output via autocomplete suggestions in ListBox. The problem is that after typing one letter in Entry I get right output but after typing 2 or more I get empty ListBox. Here's the code.
num=input()
num=int(num)
sv=StringVar()
def callback(sv,list,num):
a=sv.get()
pom_list = list
bin_list = []
lexicographic_sort(pom_list)
x = binary_search(a, pom_list)
while x != -1:
bin_list.append(x)
pom_list.remove(x)
x = binary_search(a, pom_list)
i = 0
l = Listbox(root, width=70)
l.grid(row=2, column=5)
if len(bin_list) == 0 or len(a) == 0:
l.delete(0, END)
else:
for list1 in bin_list:
if i == num:
break
l.insert(END, list1[0])
i += 1
sv.trace("w", lambda name, index, mode, sv=sv: callback(sv,list,num))
te = Entry(root, textvariable=sv)
te.grid(row=1,column=5)
where list outside callback function is a list of all suggestions, and bin_list is a list of suggestions of StringVar.get() using binary_search.
It is because all matched items for the first letter have been removed from the search list. You should use a cloned search list in callback(). Also don't create new list to show the result list, create the result list once and update its content in callback().
Furthermore, sort the search list beforehand:
def callback(sv, wordlist, num):
result.delete(0, END) # remove previous result
a = sv.get().strip()
if a:
pom_list = wordlist[:] # copy of search list
#lexicographic_sort(pom_list) # should sort the list beforehand
x = binary_search(a, pom_list)
while x != -1 and num > 0:
result.insert(END, x)
pom_list.remove(x)
num -= 1
x = binary_search(a, pom_list)
...
lexicographic_sort(wordlist)
sv = StringVar()
sv.trace("w", lambda *args, sv=sv: callback(sv, wordlist, num))
...
result = Listbox(root, width=70)
result.grid(row=2, column=5)

quiz in tkinter, Index out of range

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

Categories

Resources