[Python gadget--implementing the dot connector function from 0 to 1]

Preface

Because I need to do something, I need to use a connecting device. I looked around, but there is no one that can be used (in fact, I want to make it myself). I don't want to be angry about this. If there is no one, I can make it myself. Thinking of the python I had learned, it was time to pick it up again and play around with it, so I started to make my own dot-connector. According to my idea, you can also make some gadgets of your own.

Preparation

Environment setup

python & vscode

I won’t go into detail about setting up the environment here. You can find many tutorials on your own and just follow them. I use vscode here, mainly because I’m used to it and have feelings for it!

Make your own needs

Before doing it, you must know what you want to do. Here, I want to make a dot connector. So what kind of functions should this dot connector have? Next, let’s work together think.
First of all, as a dot connector, the most basic function is of course the ability to click continuously, so our first requirement appears:
1. You can click the screen continuously
Of course, this is also the most basic function, so let’s continue to think about where on the screen we should click. Can we let him click wherever he clicks? Do we need to record a position coordinate here? This is our second requirement:
2. Select the coordinates that need to be clicked
At this time, connect The basic prototype of the clicker has been completed, so we should add more functions. For example, how often do we click? In other words, how often do we click on the screen? I put forward my third requirement:
3. Optional click frequency
Then the click frequency is also available, and then there must be clicks. times, you can enter the number of clicks to set the number of times to connect. This is the fourth requirement I raised for myself:
4. Optional number of clicks
Finally, it would be great to have a visual interface to operate!
5. Visual interface
The basic requirements are almost there, and then you can implement it step by step according to your own needs!

Solve your own needs

The requirements are almost known. The next step is to kill them one by one and start writing code. The order of implementation may vary.

Create a visual interface

For user convenience, a simple visual interface can be designed. First create the main window root and set the theme style.
Next create GUI elements:
1. Create button – select click point

	select_point_button = ttk.Button(root, text="选择点击点", command=start_listening)
	select_point_button.pack(padx=20, pady=10)

2. Create a drop-down menu – select the click interval

    interval_var = tk.StringVar()
    interval_var.set("1s")  #
    interval_label = ttk.Label(root, text="选择点击时间间隔:")
    interval_label.pack()
    interval_menu = ttk.Combobox(root, textvariable=interval_var, values=["10ms", "100ms", "1s"])
    interval_menu.pack()

3. Create an input box – enter the number of clicks

    click_count_label = ttk.Label(root, text="输入点击次数:")
    click_count_label.pack()
    click_count_entry = ttk.Entry(root)
    click_count_entry.pack()

4. Create a button – start simulating a click

    simulate_clicks_button = ttk.Button(root, text="开始模拟点击", command=simulate_continuous_clicks)
    simulate_clicks_button.pack(padx=20, pady=10)

5. Create a text box for recording information

    info_text = tk.Text(root, height=5, width=40, state=tk.DISABLED)
    info_text.pack(padx=20, pady=10)

Finally, the GUI loop is started, waiting for user interaction.

    root.mainloop()

The interface rendering is as follows:
Insert image description here

Get click points

To obtain the mouse or keyboard, you need to use the Listener and KeyboardListener of the pynput library to listen for mouse click events and keyboard events.

with Listener(on_click=record_click_point) as listener, KeyboardListener(on_release=on_key_release) as keyboard_listener:

This line of code uses the pynput library to create two listener objects: listener and keyboard_listener, which are used to monitor mouse click events and keyboard key release events respectively. This is a context manager (with statement) used to ensure that listeners are started and stopped correctly when entering and exiting a with block.
on_click=record_click_pointTells the listener to call when a mouse click event is detectedrecord_click_pointFunction.
When the user presses the button to select the click point, monitoring of mouse click events will be started

def start_listening():
    global listening
    listening = True
    recorded_info = "请点击屏幕上的一个点"
    info_text.config(state=tk.NORMAL)
    info_text.delete(1.0, tk.END)
    info_text.insert(tk.END, recorded_info)
    info_text.config(state=tk.DISABLED)

The next step is to implement therecord_click_point function to record the coordinates of the user's click.

def record_click_point(x, y, button, pressed):
    global selected_point, point_selected, listening
    if listening:
        if pressed:
            selected_point = (x, y)
            point_selected = True
            recorded_info = f"已选择点击点:{
      
      selected_point}"
            info_text.config(state=tk.NORMAL)
            info_text.delete(1.0, tk.END)
            info_text.insert(tk.END, recorded_info)
            info_text.config(state=tk.DISABLED)
            listening = False  # 停止监听

The function of this function is to record the coordinates of the click point selected by the user when the user clicks the mouse and is listening to the mouse event, and updates the text box in the GUI interface to display the selected click point information. Once the selection is complete, the function stops listening for mouse events.

Set click interval and number of clicks

1. Get the click time interval
Set the value of the global variable click_interval according to the click time interval selected by the user in the drop-down menu

def set_click_interval():
    global click_interval
    selected_interval = interval_var.get()
    if selected_interval == "10ms":
        click_interval = 0.01
    elif selected_interval == "100ms":
        click_interval = 0.1
    elif selected_interval == "1s":
        click_interval = 1.0

The purpose of this function is to convert the click time interval into seconds represented by a floating point number according to the user's selection, and store it in click_interval so that subsequent click operations can use this time interval. When the user selects different time intervals in the GUI, this function updates the value of click_interval based on the selection. This way, users can customize the speed of clicks as needed.
2. Get the number of clicks
Set the value of the global variable click_count according to the number of clicks entered by the user in the input box. There is a small easter egg hidden here, enter the special field Unlimited clicks are possible.

def set_click_count():
    global click_count, infinite_clicks
    input_count = click_count_entry.get()
    if input_count.lower() == “手动马赛克":
        infinite_clicks = True
    else:
        try:
            click_count = int(input_count)
            infinite_clicks = False
        except ValueError:
            recorded_info = "请输入有效的点击次数或 '手动马赛克' 进行无限次点击"
            info_text.config(state=tk.NORMAL)
            info_text.delete(1.0, tk.END)
            info_text.insert(tk.END, recorded_info)
            info_text.config(state=tk.DISABLED)
            return

The purpose of this function is to set the value of the global variable click_count and the state of the infinite_clicks flag based on user input. If the user enters a valid integer, the number of clicks will be set to that integer value and the infinite_clicks flag will be set to False, indicating that the specified number of clicks will be performed. If the user enters the special value "Manual Mosaic", it means unlimited clicks. If the user enters something other than a valid integer, an error message will be displayed.

Continuous clicks

To simulate a click operation in the background, the code is as follows:

def simulate_clicks_background():
    global selected_point, clicking, infinite_clicks
    mouse = Controller()
    recorded_info = "正在进行点击"
    info_text.config(state=tk.NORMAL)
    info_text.delete(1.0, tk.END)
    info_text.insert(tk.END, recorded_info)
    info_text.config(state=tk.DISABLED)
    # 模拟连续点击选定的点
    if infinite_clicks:
        while clicking:
            mouse.position = selected_point
            mouse.click(Button.left)
            time.sleep(click_interval)  # 等待指定的时间间隔
    else:
        for _ in range(click_count):
            if not clicking:
                break  # 用户按下了停止按钮,结束点击
            mouse.position = selected_point
            mouse.click(Button.left)
            time.sleep(click_interval)  # 等待指定的时间间隔
    clicking = False
    recorded_info = "模拟点击完成"
    info_text.config(state=tk.NORMAL)
    info_text.delete(1.0, tk.END)
    info_text.insert(tk.END, recorded_info)
    info_text.config(state=tk.DISABLED)
    point_selected = False  # 重置选择的点击点状态

mouse = Controller() This line creates a pynput.mouse.Controller object to simulate mouse click operations.
mouse.position = selected_pointThis line moves the mouse to the click point selected by the user (the coordinates of selected_point).
mouse.click(Button.left) This line simulates the left mouse button click operation.
time.sleep(click_interval) This line sleeps (pauses execution) for a period of time and waits for the specified time interval click_interval.
The function of this function is to simulate mouse click operations in the background. It can perform unlimited clicks or a specified number of clicks according to the mode selected by the user, and update the text box in the GUI interface after completion. to display the corresponding information.

test

A simple dot connector is complete, and I can't wait to test its functionality. In order to improve the function, I have also added the function of stopping clicking. Although I have not mentioned it in detail before, I believe that attentive friends have discovered it. Okay, without further ado, let’s just start testing. I have to say that video review is really slow.

Connector test video

Now you can have fun playing!

Guess you like

Origin blog.csdn.net/a1379292747/article/details/132969512