线程和Tkinter不能一起使用 [英] Threads and Tkinter not working together

查看:137
本文介绍了线程和Tkinter不能一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用简单的自动答题器练习Tkinter,Pyautogui和线程.

Trying to practice Tkinter, Pyautogui and threading with a simple (or so I thought) auto clicker.

  • 应该打开一个菜单(选中),
  • 然后选择按钮(选中),
  • 它打开另一个窗口(选中),
  • ,当您按下 F7 时,它将开始单击(不起作用)
  • It is supposed to open up a menu (check),
  • then a choice of buttons (check),
  • it opens up another window (check),
  • and when you press F7 it starts clicking (not working)

这在没有Tkinter的情况下也很好

This works fine without Tkinter

这是代码:

from tkinter import *
from pyautogui import *
from time import  *
from threading import Thread as th
import keyboard 

root = Tk()
key_loop = 1
k = ""
root.geometry("150x500")
def detect_key_def():
    global k
    while key_loop == 1:
        if keyboard.is_pressed('f7'):
            k = "f7"
        elif keyboard.is_pressed("f8"):
            k = "f8"
        elif keyboard.is_pressed("f9"):
            k = "f9"

detect_key = th(target=detect_key_def)
detect_key.start()
def clicker():
    clicker = Tk()
    root.geometry("300x300")

Label(clicker, text="Start - F7\n\nStop - F8").pack()
Button(clicker, text="Exit", command =clicker.destroy).pack()
if k == "f7":
    click()
    t.sleep(0.01)
elif k == "f8":
    t.sleep(0.01)
clicker.mainloop()

Button(root, text="Auto Clicker", command=clicker).pack()
root.mainloop()

当我运行代码时, F7 启动器不起作用.
有什么想法吗?

When I run the code the F7 starter does not work.
Any ideas?

推荐答案

好吧,因此根据您尝试对代码执行的操作,最好在此处使用after()而不是线程. Tkinter始终监视所有按键,因此您只需将F7按钮绑定到顶层"窗口即可.

Ok so based on what you are trying to do with your code it is probably best to use after() here instead of threading. Tkinter monitors all the key presses anyway so you can just bind the F7 button to the Toplevel window.

以下代码将F7绑定到Clicker顶层窗口.单击顶层以使其聚焦时,可以使用F7来启动自动单击.我将其设置为每秒1次点击.

The below code will bind F7 to the clicker toplevel window. When you click in toplevel to give it focus you can use the F7 to start the auto clicking. I have it set to 1 clicks a second.

import tkinter as tk
from pyautogui import click

root = tk.Tk()
key_loop = 1
root.geometry("150x500")

def click_loop(event=None):
    click()
    root.after(100, click_loop)

def clicker():
    clicker = tk.Toplevel(root)
    root.geometry("300x300")
    tk.Label(clicker, text="Start - F7\n\nStop - F8").pack()
    tk.Button(clicker, text="Exit", command =clicker.destroy).pack()
    clicker.bind("<F7>", click_loop)

tk.Button(root, text="Auto Clicker", command=clicker).pack()
root.mainloop()

这篇关于线程和Tkinter不能一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆