This question already has answers here:
'>' not supported between instances of 'IntVar' and 'IntVar'
(2 answers)
Closed 7 months ago.
In python using tkinter. I'm trying to let a user enter a number into an entry box, the number they enter will be the number a loop starts on. An error appears saying: TypeError: '<' not supported between instances of 'IntVar' and 'int'.
root = tk.Tk()
x = tk.IntVar(value=1)
EnterNumber = tk.Label(root, text='Starting server:')
EnterNumber.config(font=('helvetica', 10))
canvas.create_window(100, 680, window=EnterNumber)
Message = tk.Entry(root, textvariable=x)
canvas.create_window(232, 680, height=40, width=50, window=Message)
def Typing():
time.sleep(5)
global x
while x < 212 and not keyboard.is_pressed("q"): #error is here
pyautogui.moveTo(Search)
click()
X = str(x)
s = "smalltribes"
S = str(s)
U = " "
T = S+X+U
pyautogui.write(T)
time.sleep(1)
x += 1
Not all of the code is included just what I thought is needed.
You need to use x.get() wherever you are trying to compare the value of x to something. That is how you get the value that is stored in a tkinter custom variable.
Related
This question already has answers here:
Lambda in a loop [duplicate]
(4 answers)
Closed 5 months ago.
I have the following code to create a group of labels, with label_click_handler running when one of them is clicked:
def label_click_handler(i):
print("Label " + str(i) + " pressed")
# etc.
for i in range(10):
label = Label(text="Label " + str(i))
label.place(x=i*50, y=0)
label.bind("<Button-1>", lambda e:label_click_handler(i))
My issue is that clicking on any of the buttons will print the message:
Label 9 pressed
So the value of 9 (last in the range) is passed through to label_click_handler no matter which button is pressed.
How can I make the number of the button pressed get passed to label_click_handler?
Set i=i in the lambda function so i default value in function is set to the current i value.
def label_click_handler(i):
print("Label " + str(i) + " pressed")
# etc.
for i in range(10):
label = Label(text="Label " + str(i))
label.place(x=i*50, y=0)
label.bind("<Button-1>", lambda e,i=i:label_click_handler(i))
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
So basically, I am making a guessing game in Tkinter. I am comparing numbers to check if the number the user has guessed is greater, lesser, or the same compared to the randomly generated number. I am getting an error about my operator so please provide the correct code, thanks. Here is my code:
from tkinter import messagebox
import random
from tkinter import *
root = Tk()
r = random.randint(1,100)
root.title("Game thing")
def clear():
number_entry1.delete(0,END)
def quit():
exit()
def Guessnumber():
if number_entry1.get() > int(r):
m1 = messagebox.showinfo("Sorry","Lower")
elif number_entry1.get() < int(r):
m2 = messagebox.showinfo("Sorry","Higher")
else:
m3 = messagebox.showinfo("Congratulations","You Got It!")
message_label = Label(root,text = "Guess the number form (1 - 100)")
message_label.grid(row = 0, column = 0)
number_entry1 = Entry(root)
number_entry1.grid(row = 0, column = 1,columnspan = 2)
guess_button = Button(root,text = "Guess Number",fg = "green",command = Guessnumber)
guess_button.grid(row = 1, column = 0, sticky = W)
clear_button = Button(root,text = "Clear",fg = "blue",command = clear)
clear_button.grid(row = 1, column = 1, sticky = W)
quit_button = Button(root,text = "Quit",fg = "red",command = exit)
quit_button.grid(row = 1, column = 2, sticky = E)
Thanks!!! Also if you could I would like an explanation on why I am getting an error.
Again thanks for all the help everyone
The error (which you should have provided in the question but I already detected it) is caused because You compare a string with an integer here:
def Guessnumber():
if number_entry1.get() > int(r):
m1 = messagebox.showinfo("Sorry","Lower")
elif number_entry1.get() < int(r):
m2 = messagebox.showinfo("Sorry","Higher")
else:
m3 = messagebox.showinfo("Congratulations","You Got It!")
Why? because using the .get() method of Entry widgets returns the value of what was entered in the widget as a string, so the simple solution would be this:
def Guessnumber():
if int(number_entry1.get()) > int(r):
m1 = messagebox.showinfo("Sorry","Lower")
elif int(number_entry1.get()) < int(r):
m2 = messagebox.showinfo("Sorry","Higher")
else:
m3 = messagebox.showinfo("Congratulations","You Got It!")
Oh, and also to mention, this is not necessary: int(r), because the function random.randint(1,100) already returns an integer so converting it again is redundant.
And also the function quit() is quite useless since the only thing defined there is the built-in exit() which actually is the same length as in characters so kinda pointless without other functionality
The "final version" of how that function "should" (to the best practices I know) look is this (also includes some PEP 8 - Style Guide for Python Code suggestions and also that there is now only one .get() call which theoretically improves performance since now the method in all cases has to be called only once):
def guess_number():
user_input = int(number_entry1.get())
if user_input > r:
messagebox.showinfo("Sorry", "Lower")
elif user_input < r:
messagebox.showinfo("Sorry", "Higher")
else:
messagebox.showinfo("Congratulations", "You Got It!")
This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 2 years ago.
I want to make a calculator that adds 10 to the number using tkinter.
But I had to get the entry price in int format, so I used get method.
I keep getting the following error message. What's the problem?
from tkinter import *
window=Tk()
a=Entry(window)
a.pack()
b=a.get()
c=int(b)
result2=Label(window,text="")
result2.pack()
def Button_Press():
global c
result=c+10
result2.config(text=result)
button=Button(window,command=Button_Press())
button=pack()
window.mainloop()
Here's the error text.
c=int(b)
ValueError: invalid literal for int() with base 10: ''
ValueError: invalid literal for int() with base 10: ''
Has show you that the c is ''(a string which length is zero).The code seems to be int('').That's why it will raise exception.
Your code could be:
from tkinter import *
window = Tk()
a = Entry(window)
a.insert("end", "0") # just insert a str "0"
a.pack()
b = a.get()
c=int(b)
print(c)
result2 = Label(window, text="")
result2.pack()
def Button_Press():
result = c + 10
result2.config(text=result)
button = Button(window, command=Button_Press) # there is no "()"
button.pack() # not button = pack()
window.mainloop()
This question already has answers here:
Interactively validating Entry widget content in tkinter
(10 answers)
Closed 8 years ago.
I am trying to make a basic calculator in python tkinter. I made an entry box that user types his first number into. But then, what if someone enters in something other than numbers, but text? My question is, how to make that you can put only number to entry box, or how it can ignore normal letters.
By the way, my half-done code is here:
from tkinter import *
okno = Tk()
okno.title("Kalkulačka")
okno.geometry("400x500")
firstLabel = Label(text="Vaše první číslo").place(x=25, y=25)
firstInput = Entry(text="Vaše první číslo").place(x=130, y=25, width=140)
buttonplus = Button(text="+").place(x=130, y=75)
buttonminus = Button(text="-").place(x=165, y=75)
buttonkrat = Button(text="・").place(x=197, y=75)
buttondeleno = Button(text=":").place(x=237, y=75)
What I would do personally is run every user input through an integer verifying function before accepting it as input. Something simple like this:
def is_int(x):
try:
x = int(x)
return True
except:
return False
This question already has answers here:
Making a string out of a string and an integer in Python [duplicate]
(5 answers)
Closed 8 years ago.
Here is a simplified snapshot of my code:
def getExamPoints(examPoints):
totalexamPoints = 0
return totalexamPoints
def getHomeworkPoints(hwPoints):
totalhwPoints = 0
return totalhwPoints
def getProjectPoints(projectPoints):
totalprojectPoints = 0
return avgtotalprojectPoints
def computeGrade(computeGrade):
computeGrade = 1
return computeGrade
def main ( ):
gradeReport = "\n\nStudent\t Score\tGrade\n=====================\n"
studentName = input ("Enter the next student's name, or 'quit' when done: ")
while studentName != "quit":
examPoints = getExamPoints(studentName)
hwPoints = getHomeworkPoints(studentName)
projectPoints = getProjectPoints(studentName)
studentScore = examPoints + hwPoints + projectPoints
studentGrade = computeGrade (studentScore)
gradeReport = gradeReport + "\n" + studentName + "\t%6.1f"%studentScore + "\t" + studentGrade**
main ( ) # Start program
Getting an error on gradeReport assignment on last line which says "can't convert int object to str implicitly". Why is it so?
This is the line in question:
gradeReport = gradeReport + "\n" + studentName + "\t%6.1f"%studentScore+"\t"+studentGrad
You should use string formatting instead of simply adding strings and ints together (which is an error). One way would be:
gradeReport = '%s\n%s\t%6.1f\t%s' % (gradeReport, studentName, studentScore, studentGrade
There are other ways, but since you were already using % formatting, I've continued that here
In Python, "5" + 5 is an error, because it's ambiguous. Should it return "55"? 10? Rather than make assumptions and be wrong half the time, Python requires you to be explicit about it.