Michael
Michael

Reputation: 27

Python Object is not Iterable

When I run this code of a spambot it gives me the error that the "'StringVar' object is not iterable", I am new to python and I don't really know exactly what that means, if you can help me with an working code of this please post it.

I don't exactly know that the other part of the code is fully working but I made a console one and it s perfectly working.

import tkinter as tk
from pynput.keyboard import Key, Controller
import time

keyboard = Controller()

def spam():

time.sleep(2)

    while True:

        for char in var:
            keyboard.press(char)
            keyboard.release(char)
            time.sleep(0.12)

root = tk.Tk()

var = tk.StringVar()

root.geometry("500x300")

write = tk.Label(text="Insert sentence then print the button:")
button = tk.Button(text="Spam", command = spam)
enter = tk.Entry(root, textvariable = var) 

write.pack()
enter.pack()
button.pack()

root.mainloop()

Upvotes: 0

Views: 4562

Answers (1)

Isaac Saffold
Isaac Saffold

Reputation: 1185

StringVar is a wrapper for a string, not the string itself. To access the string it contains, try for char in var.get(): instead of for char in var:. Strings are iterable in Python, so that will work.

That something is "iterable" in Python means that it has a method called __iter__ that, when called, returns an iterator that can in turn be called to loop through the elements it contains, one by one. A for loop implicitly calls an object's __iter__ method to access its iterator. Read https://docs.python.org/3/tutorial/classes.html#iterators for a more detailed explanation.

Upvotes: 1

Related Questions