如何在GUI按钮上启动while循环?

时间:2015-11-20 16:42:13

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

我正在寻找一种方法来按下按钮启动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

1 个答案:

答案 0 :(得分:0)

你需要传递Button构造函数&#34;命令&#34;关键字:

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