【问题标题】:How to start a while loop on GUI button press?如何在 GUI 按钮按下时启动 while 循环?
【发布时间】:2015-11-20 16:42:13
【问题描述】:

我正在寻找一种在按下按钮时启动 while 循环的方法,在本例中是名为“start_loop”的按钮。我非常想知道这是如何完成的,并感谢您在完成此过程中提供的任何帮助,谢谢!


这是完整的 Python 脚本:

from tkinter import *
import win32api
import win32con
from tkinter import messagebox


# defining click as setting the position and starting a click and ending a click
def click(x, y):

    win32api.SetCursorPos((x, y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0,  0)

# Creation of the GUI below

root = Tk()
root.geometry('315x250+250+250')  # 315x250 and 250 pixels in x and y direction
root.title("Buffet Time's Auto-Clicker")

# Click
click_label = Label(text='Enter # of clicks here:', fg='green').place(x=30, y=30)
click_entry = Entry().place(x=150, y=30)

# X
x_label = Label(text='Enter the x coordinate here:', fg='black').place(x=30, y=75)
x_entry = Entry().place(x=150, y=75)

# Y
y_label = Label(text='Enter the y coordinate here:', fg='blue').place(x=30,     y=120)
y_entry = Entry().place(x=150, y=120)

# Start the loop button
start_loop = Button(text='Press to Start', fg='yellow', bg='black').place(x=110,    y=175)


# prompts user before quitting
def on_closing():
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        root.destroy()
root.protocol("WM_DELETE_WINDOW", on_closing)

root.mainloop()

num_of_clicks = click_entry.get()
x_coord = x_entry.get()
y_coord = y_entry.get()


# while loop for the clicking
counter = 0
try:
    while counter < num_of_clicks:
        click(x_coord, y_coord)  # 230, 475 for cookie clicker

        if win32api.GetAsyncKeyState(ord('X')):
            break
        counter += 1
except KeyboardInterrupt:
    pass

【问题讨论】:

    标签: python user-interface button while-loop tkinter


    【解决方案1】:

    您需要将“command”关键字传递给 Button 构造函数:

    start_loop = Button(root, text='Press to Start', fg='yellow', bg='black', command=self.myButtonHandler).place(x=110, y=175)
    

    并定义一个函数 myButtonHandler(frame),每次按下按钮时都会调用该函数,因此计数器会加 1。

    这就是你所追求的吗?循环隐藏在 root.mainloop 中,您不必自己编写循环。您的退出按钮的命令应该是 frame.quit

    【讨论】:

    • 我正在尝试做的是制作这个 GUI,它在 while 循环中为三个变量中的每一个变量提供输入,然后一旦按下“Press to Start”按钮,自动点击器就会启动然后它会一直点击,直到完成点击次数或按下“X”,这会杀死循环。有没有我可以将while循环嵌入到按钮中,这样当按下按钮时,While循环就会运行?
    • 听起来你需要两个线程 - 抱歉,我的 Python 达不到这个要求!
    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 2020-06-01
    • 2015-07-19
    • 2017-09-25
    • 2012-07-14
    • 2012-04-02
    • 2020-12-29
    • 2018-03-20
    相关资源
    最近更新 更多