为什么它说 a isnt defined 即使我已经定义了你

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

所以我定义了 a 但是当我尝试使用 keybaord.type 键入 a 时它只是说它没有定义 我尝试制作一个没有用的全局我尝试移动代码的位置但没有用我尝试了很多其他的东西他们也没有用

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()
def webop() 下的

global a 使 webop 可以访问封闭范围内的变量 a(您正在执行导入的范围)。由于您尚未在该范围内定义 a,因此出现错误。

无论哪种方式,您通常应该避免使用这样的全局变量,并使用参数将数据传递给函数。为了将参数传递给您的 Button command,您可以使用闭包。

您应该将访问 a 的代码部分移动到设置该值的部分

目前还不清楚你想在这里实现什么,因为当你 运行 webop 你的程序将到达 while True 并不断循环到那里并且永远不会到达你下面的代码循环

例如

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)

另一种方法使用 functools partial 实现同样的目的。参见 https://www.delftstack.com/howto/python-tkinter/how-to-pass-arguments-to-tkinter-button-command/