Bálint Ember
Bálint Ember

Reputation: 1

In tkinter, it showed "TypeError: not all arguments converted during string formatting"

def kiir2():
    if sz1.get()%2==0:
        prs1=Label(ablak,text=sz1.get())
        prs1.grid(row=4,column=2)
    elif sz3.get()%2==0:
        prs2=Label(ablak,text=sz3.get())
        prs2.grid(row=4,column=2)
    elif sz5.get()%2==0:
        prs3=Label(ablak,text=sz5.get())
        prs3.grid(row=4,column=2)

And I get the error:

TypeError: not all arguments converted during string formatting

How can i fix this?

Upvotes: 0

Views: 32

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385960

.get() returns a string. %2 is trying to do string formatting, not a modulo operation. If you're trying to do a modulo operation, you need to convert the value to an int.

if int(sz1.get())%2 == 0:
   ...

A better practice, however, is to do the conversion and the math in separate steps, since the conversion could throw errors due to bad data (user not entering anything, the user entering a non-integer, etc).

try:
    sz1_value = int(sz1.get())
Except ValueError:
    <code to handle bad user input>
...
if sz1_value % 2 == 0:
    ...

Upvotes: 1

Related Questions