【发布时间】:2021-09-26 15:08:39
【问题描述】:
所以我使用了线程,所以我可以在 Tkinter 中使用 while 循环。 代码如下(主要思想是有一个介绍屏幕,您可以在其中按下一个按钮并打开游戏):
def start_game_thread():
threading.Thread(Target=root.after(3000,start_game()).start())
def searching_loop(start_point, goal):
while True:
pure_goal = goal.current_url
start_point_temp = start_point.current_url
if pure_goal != goal.current_url:
goal.get(pure_goal)
print("I am the goal, you cannot change me")
if start_point_temp != start_point.current_url:
start_point_temp = start_point.current_url
if goal.current_url == start_point.current_url:
start_point.quit()
goal.quit()
def start_game():
start_point = exction()
set_main_page(start_point, 'https://en.wikipedia.org/wiki/Main_Page')
goal = exction()
set_main_page(goal, 'https://en.wikipedia.org/wiki/Main_Page')
clicker(start_point, 'Random article')
clicker(goal, 'Random article')
searching_loop(start_point, goal)
这是主要的:
root = Tk()
root.geometry("1920x1080")
EnterTheGame = Button(root, text="Enter The Game", command=lambda :start_game_thread())
EnterTheGame.place(x=960, y=540)
root.mainloop()
由于某种原因,它似乎不起作用,我是线程新手,任何帮助都可以帮助我:)
更新 1:
def start_game():
root.withdraw()
start_point = execution()
set_main_page(start_point, 'https://en.wikipedia.org/wiki/Main_Page')
goal = execution()
set_main_page(goal, 'https://en.wikipedia.org/wiki/Main_Page')
clicker(start_point, 'Random article')
clicker(goal, 'Random article')
searching_loop(start_point, goal)
root.deiconify()
执行此操作后,问题解决,网络浏览器在我单击按钮后立即运行,没有问题,但是当我在游戏完成后尝试重新打开我的根目录时,问题就开始了。
[WinError 10061] No connection could be made because the target machine actively refused it
屏幕可以正常工作,但它会不断打印很多错误,并且还会降低我的 CPU 速度。
更新 2:
在searching_loop 循环中添加一个中断设法解决了错误问题,但 deiconify() 将我检索回介绍屏幕
更新 3: 正如@TheLizzard 所建议的那样,我刚刚使用 .config(text="") 更改了我的按钮,并且效果很好:)
非常感谢。
【问题讨论】:
-
查看
.after脚本。您可以实现.after脚本循环。也不要在多个线程中使用tkinter。有时tkinter甚至会在没有回溯的情况下崩溃。 -
我还是 Tkinter 的新手,你介意我们可以在私人房间里讨论吗?我不想在这里向 cmets 发送垃圾邮件。
-
这不是私人咨询服务。如果你有问题,其他人也会有同样的问题,他们可以从你的讨论中受益。所有 GUI 操作都必须来自主线程。如果您有一个按钮操作需要运行一个长进程,那么让按钮调用一个函数,并让该函数调用线程。在你的情况下,你应该在主线程中调用
root.after,并在那个函数中创建你的线程。 -
除非您给出一个最小的工作示例,否则我无能为力。还可以尝试查看this。看看他们是如何在那里实现一个while循环的。
-
@TimRoberts 它不必在主线程中。它只需要在您创建
Tk()窗口的同一线程中即可。但这只是一个小提示
标签: python multithreading selenium tkinter