Search code examples
python-3.xtkinterpynput

Why is it saying a isnt defined even though i have defined you


so i defined a but when i try to type out a using keybaord.type it just says that it isnt defined i tried making a global that didnt work i tried moving postions of the code and that didnt work ive tried many other things they didnt work either

from tkinter import *
import webbrowser
from pynput.keyboard import Key, Controller
import time
menu = Tk()
menu.geometry('200x300')

def webop(): # new window definition
    global a

    def hh():
        a = "" + txt.get()
    while True:
        keyboard = Controller()
        time.sleep(1)
        keyboard.type(a)
        keyboard.press(Key.enter)
        keyboard.release(Key.enter)

    sp = Toplevel(menu)
    sp.title("Spammer")
    txt = Entry(sp, width=10)
    txt.grid(row=1,column=1)
    btn = Button(sp, text='spam', command=hh)
    btn.grid(row=1,column=2)





def enc():
    window = Toplevel(menu)
    window.title("nou")

button1 =Button(menu, text ="Spammer", command =webop) #command linked
button2 = Button(menu, text="Fake bot", command = enc)
button1.grid(row=1,column=2)
button2.grid(row=2,column=2)
menu.mainloop()

Solution

  • global a underneath def webop() gives webop access to the variable a in the enclosing scope (the scope up there where you're doing your imports). Since you haven't defined a in that scope, you're getting the error.

    Either way, you generally should avoid using globals like that and pass data to functions using arguments. In order to pass arguments into your Button command you can use a closure.

    You should move the part of your code accessing a to the part where that value is set

    It is unclear what you're trying to achieve here since when you run webop your program will reach while True and continuously loop there and never reach the code below your while loop

    For instance

    def hh(a):
        a = "" + txt.get()
        while True:
            keyboard = Controller()
            time.sleep(1)
            keyboard.type(a)
            keyboard.press(Key.enter)
            keyboard.release(Key.enter)
    
    btn = Button(sp, text='spam', command=hh)
    

    An alternative approach achieves the same thing using functools partial. See https://www.delftstack.com/howto/python-tkinter/how-to-pass-arguments-to-tkinter-button-command/