How to make autoclicker in python with GUI? - python

I try make own autoclicker with GUI but I don't know how make CPS(Clicks per second).
I have tried in different ways but nothing work. Please for help with solution on this problem.
from tkinter import *
import time
running = False
cps_counter = 0
def scanning():
global cps_counter
cps_chk = cpscheck.get()
delay = 1/int(cps_chk)
if running:
cps_counter += 1
label.configure(text=f'{cps_counter}')
time.sleep(delay)
def start():
global running
if running == False:
running = True
else:
running = False
window = Tk()
window.title("Title")
window.geometry("500x500")
start = Button(window, text="Start/Stop Scan", command=start)
start.grid()
cpscheck = StringVar()
textBox = Entry(bd=0, bg="#545454", highlightthickness=0, textvariable=cpscheck, font=("Helvetica", 20), fg="white", justify='center')
textBox.place( x=250, y=123, width=85.0, height=25)
label = Label(text=cps_counter)
label.place(x=100, y=100)
window.after(100, scanning) # After 1 second, call scanning
window.mainloop()

Related

Program lines are executing immediately before returning from function calls in python. Please explain program flow in event driven program

When the start timer is called by the button click, how is it that the lines following the count_down function call are executed immediately before the counter is completed and returned?
Also, if we double click the start button it behaves weirdly.
Please explain the program flow in event-driven programs in python.
from tkinter import *
import math
def start_timer():
work_sec = 15
count_down(work_sec)
timer_label.config(text="Work", fg="red")
print("Debug")
def count_down(count):
count_min = math.floor(count/60)
count_sec = count % 60
canvas.itemconfig(timer_text, text=f"{count_min}:{count_sec}")
if count > 0:
window.after(1000, count_down, count-1)
window = Tk()
timer_label = Label(text="Timer", fg="green", font=("Courier", 48, "bold"))
timer_label.pack()
canvas = Canvas(width=300, height=250, bg="black")
timer_text = canvas.create_text(150, 125, text="00:00", fill="white", font=("Arial", 35))
canvas.pack()
start_button = Button(text="start", command=start_timer)
start_button.pack()
window.mainloop()
The point of tk.after is that it doesn't freeze the GUI. In the code count_down updates the count and the canvas and then returns to keep the GUI responsive. In the code below I've added some print statements which show what's being called when in the console. I hope this makes the sequence of calls more obvious. Try clicking the 'start' button more than once a few seconds apart.
import tkinter as tk
from math import floor
start_timer_count = 0
def start_timer():
global start_timer_count
start_timer_count += 1
print( f"start_timer_called for {start_timer_count} th time." )
work_sec = 15
count_down(work_sec, start_timer_count )
print("start_completes")
def count_down(count, start_count ):
print( f"count_down called. count = {count}. Called by start_timer {start_count}." )
count_min = floor(count/60)
count_sec = count % 60
canvas.itemconfig(timer_text, text=f"{count_min}:{count_sec}")
if count > 0:
window.after(1000, count_down, count-1, start_count )
window = tk.Tk()
timer_label = tk.Label(text="Timer", fg="green", font=("Courier", 48, "bold"))
timer_label.pack()
canvas = tk.Canvas(width=300, height=250, bg="black")
timer_text = canvas.create_text(150, 125, text="00:00", fill="white", font=("Arial", 35))
canvas.pack()
start_button = tk.Button(text="start", command=start_timer)
start_button.pack()
window.mainloop()

Unable to label text using config in tkinter

So, I have been trying to create a simple stopwatch in tkinter in which I created a loop to update text to new time i.e., the next second in timer label as I click button_1. I tried to do this with StringVar() as well as .config method but none of them are updating the text in label. The code is below
from datetime import *
from time import *
init_time = datetime(100, 1, 1, 0, 0, 0)
running = True
def clock():
while running == True:
sleep(1)
global init_time
a = init_time.strftime("%H:%M:%S")
mtime.set(a)
init_time = init_time + timedelta(seconds=1)
def stop():
global running
running = False
main = Tk()
main.geometry("500x200")
mtime = StringVar()
timer = Label(main, textvariable = mtime, width=30, bg="black", fg="white", font=(25))
timer.place(x=90, y=20)
button_1 = Button(main, text = "Start", command = clock()).place(x=170, y=120)
button = Button(main, text = "Stop", command = stop).place(x=250, y=120)
main.mainloop()
I even tried to convert the init_time to a string because I thought maybe the updates of text work only for strings. The initial GUI window shows but as I click button_1 it doesn't work.
You did common mistake, look at these two lines
button_1 = Button(main, text = "Start", command = clock()).place(x=170, y=120)
button = Button(main, text = "Stop", command = stop).place(x=250, y=120)
Note that you have clock() and stop. First is function invocation, second is function. You should provide function as command. Replace clock() using clock.
Also if you are interested in executing function every n miliseconds, please take look at .after, consider following simple timer
import tkinter as tk
elapsed = 0
def update_timer():
global elapsed
elapsed += 1
timer['text'] = str(elapsed)
root.after(1000, update_timer) # 1000 ms = 1 second
root = tk.Tk()
timer = tk.Label(root, text="0")
btn = tk.Button(root, text="Go", command=update_timer)
timer.pack()
btn.pack()
root.mainloop()

Tkinter button - Replacing old info with new when pressed

Need help solving this problem, I'm a beginner going crazy over this. Each time I press "pingButton1" I want the "pingResult1" to refresh the information insteed of adding new every time I press it. It's a simple "check if ping is good" program.
Any suggestions?
stacking
I've tried using google but nothing is working for me.
from tkinter import *
import os
import subprocess
from time import sleep
menu = Tk()
menu.title("Panel")
menu.geometry("250x380+700+500")
menu.resizable(0, 0)
menu.configure(background="#0d335d")
def close():
screen.destroy()
def pingWindow1():
global ip1
global pingButton1
global screen
screen = Toplevel(menu)
screen.title("Ping Windows")
screen.geometry("300x250+650+300")
screen.configure(background="#0d335d")
blank = Label(screen, bg="#0d335d", text="")
blank.pack()
ip1 = Entry(screen, width=20, bg="white")
ip1.pack()
blank1 = Label(screen, bg="#0d335d", text="")
blank1.pack()
pingButton1 = Button(screen, text="Ping away..", width="20", bg="#e5e5e5", height="2", borderwidth=2, relief="ridge", command=pingResult1)
pingButton1.pack()
close_ping = Button(screen, text="Close", width="20", bg="#e5e5e5", height="2", borderwidth=2, relief="ridge", command=close)
close_ping.pack()
blank2 = Label(screen, text="", bg="#0d335d")
blank2.pack()
screen.bind('<Escape>', lambda _: close())
def pingResult1():
global pingIP1
pingIP1 = ip1.get()
try:
overall_mgm()
except:
return False
try:
overall_mgm_RO()
except:
return False
done = Label(screen, text="Completed").pack()
def overall_mgm():
response = os.system("ping -c 1 sekiiws00"+pingIP1)
if response is not 0:
fail = Label(screen, bg="black", fg="red", text="KI FAILED").pack()
else:
success = Label(screen, bg="black", fg="green", text="KI SUCCESS").pack()
def overall_mgm_RO():
response = os.system("ping -c 1 seroiws00"+pingIP1)
if response is not 0:
fail = Label(screen, bg="black", fg="red", text="RO FAILED").pack()
else:
success = Label(screen, bg="black", fg="green", text="RO SUCCESS").pack()
# Widget
option = Button(menu, text="Ping IP", width="20", bg="#e5e5e5",height="2", borderwidth=2, relief="ridge", command=pingWindow1)
# Out
option.pack()
menu.mainloop()
I'm guessing I need something like this
if pingButton1 clicked more than once
refresh current Labels( fail & success)
def pingResult1():
global pingIP1
pingIP1 = ip1.get()
try:
overall_mgm()
except:
return False
try:
overall_mgm_RO()
except:
return False
done = Label(screen, text="Completed").pack()
with this demo you can change button's text (for example) when pressed.
import tkinter
from functools import partial
# partial is good for passing `function` and `its args`
def button_command(button):
# for example
button.config(text="another value")
# creating new button
# root is whatever you want
button = tkinter.Button(root, text="something")
# add command to button and passing `self`
button.config(command=partial(button_command, button))
button.pack()
adapt this example to your code and you are good to go.

How can we use an Entry to set Time on Timer? (Python, tkinter)

I started coding just a few days ago, so I hope you can help me :)
I'm trying to connect an entry with my timer. So user can choose which time they want to set. They can set the value in minutes. I already got it to get the value of the entry in my timer, but the timer won't start. I'm using tkinter to code this.
So if the user enters e.g. "3" my timer will display "03:00" but time won't start running. The console is printing no errors either. Here is my code:
from tkinter import *
from PIL import ImageTk, Image
import math
window = Tk()
window.title("u'Clock")
window.config(padx=50, pady=50, bg="#1a1c20", highlightthickness=0)
timer = None
def start_timer():
count_down(0)
def get_time():
time = input_time_do.get()
int_time = int(time)
return int_time
def count_down(count):
count = get_time()
count_min = count
count_sec = count*60 % 60
if count_min < 10:
count_min = f"0{count_min}"
if count_sec < 10:
count_sec = f"0{count_sec}"
canvas.itemconfig(timer_text, text=f"{count_min}:{count_sec}")
if count > 0:
global timer
window.after(1000, count_down, count - 1)
input_time_do = Entry(width="20", background="DarkSeaGreen")
input_time_do.insert(END, string="Set Workout Time")
input_time_do.grid(column=1, row=2, padx=10, pady=10)
start_button = Button(text="START", command=start_timer)
start_button.grid(column=1, row=6, padx=10, pady=10)
canvas = Canvas(width=400, height=266, bg="#fbf7f0", highlightthickness=0)
gym_img = ImageTk.PhotoImage(Image.open("gym1.jpg")) # PIL solution
canvas.create_image(200, 133, image=gym_img)
timer_text = canvas.create_text(200, 135, text="00:00", fill="#fbf7f0", font=
("Roboto", 30))
canvas.grid(column=1, row=1)
window.mainloop()

How do I make time.sleep() work with tkinter?

I'm trying to show a sequence of numbers on the screen at regular intervals.
I'm new to python so it may be something obvious but I have tried .after and pygame.time.wait, but neither worked.
this is the code:
from tkinter import*
from random import *
import time
my_list = []
def Create_NUM(event):
x = 0
for x in range(level + 2):
button1.destroy()
num = randint(1, 100)
my_list.append(num)
Label(root, text=num,fg="red").pack()
one.pack()
time.sleep(2)
root=Tk()
num = 0
level = 1
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
button1 = Button(bottomFrame, text="Click to start game",fg="red")
button1.bind("<Button-1>", Create_NUM)
button1.pack()
root.mainloop()
I assume you want to show new number in place of old number, not below it.
import tkinter as tk
import random
def start():
# hide button
button.pack_forget()
# run `add_number` first time
add_number(level+2)
def add_number(x):
num = random.randint(1, 100)
my_list.append(num)
label['text'] = num
if x > 0:
# repeat after 2000ms (2s)
root.after(2000, add_number, x-1)
else:
# show button again after the end
button.pack()
# --- main ---
my_list = []
level = 1
root = tk.Tk()
label = tk.Label(root)
label.pack()
button = tk.Button(root, text="Click to start game", command=start)
button.pack()
root.mainloop()
Just use this simple command in your function root.update()

Categories