为什么说即使我已经定义了您也没有定义

时间:2020-05-09 19:32:33

标签: python-3.x tkinter pynput

所以我定义了一个,但是当我尝试使用keybaord.type键入时,它只是说它没有定义 我尝试创建一个无效的全局变量,尝试移动代码的位置,而无效的ive尝试了许多其他方法,它们也都不起作用

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()

1 个答案:

答案 0 :(得分:1)

global a下的

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

无论哪种方式,通常都应避免使用此类全局变量,而应使用参数将数据传递给函数。为了将参数传递到Button command中,可以使用闭包。

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

不清楚您要在这里实现什么,因为当您运行webop时,程序将到达while True并在那里不断循环,而永远不会到达while循环下面的代码

例如

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部分实现相同的目的。参见https://www.delftstack.com/howto/python-tkinter/how-to-pass-arguments-to-tkinter-button-command/