我为我的程序编写了这段代码,当我添加 while 循环时它开始崩溃:
from tkinter import *
from tkinter import messagebox
import pyautogui
import time
#3 We define the spam command
spamming=False
**def spam():
global clickidy
clickidy=f"{tipidytype.get()}"
global spamming
spamming= not(spamming)
while spamming==True:
pyautogui.press("a")
time.sleep(1)**
#1 Lets set up our window
root=Tk()
root["bg"]="#fafafa"
root.title("Sigma clicker")
root.geometry("500x500")
root.resizable(width=False, height=False)
frame=Frame()
frame.place(relx=0,rely=0,relheight=1,relwidth=1)
#2 Now we can add interface
title = Label(frame, text="Enter the button for spamming here")
title.place(x=15, y=15)
tipidytype=Entry(frame,bg="white")
tipidytype.place(x=15, y=45)
**button = Button(frame,text=" Press/F7 ", bg="gray", command=spam)**
button.place(x=15,y=75)
root.mainloop()
当我将 while 循环更改为“if”语句时它起作用,但我需要一个无限循环。我怀疑主 tkinter 窗口循环不能与 while 循环共存。因为我的窗口停止响应,但打字正常
当您直接从函数运行无限循环时,tkinter 往往会崩溃。相反,导入线程模块并通过另一个函数运行。为了确保按下“a”,我将行
pyautogui.press("a")
更改为 print('a')
,以便我可以在终端中查看输出。请注意,clickidy 已声明,但未在代码中的任何地方使用。因此,如果您希望 clickid 作为输出,请将 print('a')
更改为 print(clickidy)
。
按下按钮后,以下代码每秒输出“a”。如果您再次按下同一按钮,它将停止。
from tkinter import *
import time
import threading
#3 We define the spam command
spamming = False
def spam():
global spamming
global clickidy
spamming = not(spamming)
clickidy=f"{tipidytype.get()}"
# Make the condition based on the button's text
if button.cget('text') == 'Start spamming':
button.config(text = 'Stop spamming')
# run thru another function using threading module
threading.Thread(target = endless_print).start()
else:
button.config(text = 'Start spamming')
def endless_print():
global spamming
global clickidy
while spamming:
print('a')
time.sleep(1)
#1 Lets set up our window
root=Tk()
root["bg"]="#fafafa"
root.title("Sigma clicker")
root.geometry("500x500")
root.resizable(width=False, height=False)
frame=Frame()
frame.place(relx=0,rely=0,relheight=1,relwidth=1)
#2 Now we can add interface
title = Label(frame, text="Enter the button for spamming here")
title.place(x=15, y=15)
tipidytype=Entry(frame,bg="white")
tipidytype.place(x=15, y=45)
button = Button(frame,text="Start spamming", bg="gray", command=spam)
button.place(x=15,y=75)
root.mainloop()