Learn how to use tkinter to set up a weekly task schedule starting from a user-selected date

Weekly, I am trying to automate downloading files at a specific time and day chosen by the user, similar to what is displayed in this image. My current challenge involves integrating an inner loop concerning root.mainloop(). I have experimented with both .after and a while loop structured like this:

def autoDownload(myDay, myHour, myMinute):
    while True:
    day = datetime.datetime.now().strftime("%A")
    hour = datetime.datetime.now().strftime("%H")
    minute = datetime.datetime.now().strftime("%M")
    if day == myDay and str(int(hour)) == myHour and str(int(minute)) == myMinute:
       DownloadButton.invoke()
       break
    root.after(60000, autoDownload(clickedDays.get(), HourSpin.get(), MinSpin.get()))

Using just .after results in

Python: maximum recursion depth exceeded while calling a Python object
, and the while loop gets stuck when the condition is met, continuously invoking DownloadButton.

Additionally, on OS X, if a button function takes longer than a few seconds, the script appears as "not responding." Is there a solution to this issue as well?

I appreciate anyone who has taken the time to read my inquiry and may be able to offer assistance. Thank you!

Answer №1

Your code has a couple of issues that need to be addressed. First off, you should remove the while True loop as Tkinter's mainloop already takes care of running an infinite loop.

Secondly, when using the after method, make sure to pass a function instead of calling it directly and passing the result.

To clarify, this:

root.after(60000, scaricaAuto(clickedDays.get(), HourSpin.get(), MinSpin.get()))

... is essentially the same as:

result = scaricaAuto(clicedDays.get(), HourSpin.get(), MinSpin.get())
root.after(60000, result)

Instead, consider passing scaricaAuto as an argument or creating a new function to call your desired function. If going with the former option, remember that you can pass arguments to the function by including them in the after call.

For instance,

root.after(60000, scaricaAuto, clickedDays.get(), HourSpin.get(), MinSpin.get())

Note that this approach will immediately execute the .get() methods instead of waiting for 60 seconds.

A more effective solution would be to modify scaricaAuto not to require any arguments upfront but rather fetch the values when needed:

def scaricaAuto():
    myDay = clickedDays.get()
    myHour = HourSpin.get()
    myMinute = MinSpin.get()

    now = datetime.datetime.now()
    day = now.strftime("%A")
    hour = now.strftime("%H")
    minute = now.strftime("%M")

    if day == myDay and str(int(hour)) == myHour and str(int(minute)) == myMinute:
       DownloadButton.invoke()
    root.after(60000, scaricaAuto)

The above implementation will continue to run as long as the GUI application is active, assuming that you have previously invoked mainloop.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Client side is receiving an unexpected format from the pyramid when using the __json__ method

As I'm configuring a Pyramid back-end along with an Angular front-end application, I encounter an issue. When Angular sends an http GET request to Pyramid, the data received on the Angular side is not as expected. It seems like the id is being recogni ...

Is it possible to generate prime numbers in Python using generators?

In an attempt to calculate prime numbers using Python, I've come up with this basic function: def isPrime(number): if number == 2: return True elif number > 1 and number % 2 != 0: for current in range(3, number): ...

Transmit basic JSON data to a gRPC server with Python

When interacting with a gRPC-enabled, reflection-enabled server using grpcurl, I can easily send requests with the following syntax: grpcurl --plaintext -d '{"test_input": "Test 1 2 3", "config": { "max_results" ...

Error Establishing a Connection with Selenium

Has anyone encountered this issue previously? I just started experiencing it on Monday. What could be causing the connection problem? When using Selenium, the browser opens but fails to load the specified URL. C:\Python34\python.exe "C:\ ...

Utilizing asynchronous instance methods with django-rq

I am looking for a solution to execute instance methods asynchronously with django-rq. I attempted the following: MyClass(object): @job def my_func(self, some_arg): # Do some stuff Unfortunately, this approach results in an AttributeError due to th ...

"Encountering a 403 error with scrapy when using an HTTPS proxy, even though

I am encountering an issue with my Scrapy 1.4.0 project running on Linux and having HttpProxyMiddleware enabled in the settings.py file: DOWNLOADER_MIDDLEWARES = { 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 10, } When I e ...

Using Python to Extract Data from an ASPX Web Page

Having some trouble with my script to scrape an ASPX website. Currently, the output is: [] Process finished with exit code 0 This is the code I'm using: import requests import bs4 url = "https://www.brightmlshomes.com/Listing/ListingSearch.as ...

Utilizing Email-Specific OAuth Authentication with Django Rest Framework, NextJS, and Simple JWT

Currently in the midst of a project involving Django Rest Framework (DRF) and NextJS, where user authentication is managed using Simple JWT. My current focus is on implementing OAuth authentication, specifically to enable users to log in solely with their ...

What is the best way to iterate through rows in a DataFrame and apply calculations to certain rows based on defined conditions?

I am presenting the following data table: ID Day Month Year Status Values 1 1 2 2021 open 10 1 1 2 2021 open 2 1 1 2 2021 close 4 1 2 3 2021 open NaN 1 2 3 2021 close 3 1 2 3 2021 NaN 0 1 3 3 2021 standing NaN 1 3 3 2021 close 15 2 ...

Python/Kivy and Android environment error: Cannot find the Pandas module

I'm currently working on developing a basic Android application using Python and Kivy. In the process, I've integrated pandas into my project. Everything runs smoothly when tested on my Windows PC, but when I try to run it on an Android environme ...

Clicking on a specific tab within a webpage in order to enable selenium to extract data

from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from t ...

The impact of random attacks on an exponential complex network

I have been attempting to replicate a random attack on an Erdos-Renyi network. The expected outcome is for the network to collapse after removing approximately 20 to 30% of the nodes. However, my results differ as the size of the giant connected component ...

Unveiling hidden HTML elements with BeautifulSoup: A step-by-step guide

Currently, I am attempting to extract video content from a specific website. Although I can locate the video link using Chrome DevTools, it remains hidden when utilizing BeautifulSoup for extraction. I am hoping for assistance in modifying the code below t ...

Tips for updating a string in a Pandas column depending on a specific criteria?

I'm currently working on a task to verify if the values in a certain column are numbers and replace them with different strings. Below is the code snippet I am using: df["recs"] = ["45", "emp1", "12", "emp3", "emp4", "emp5"] recomm = df["recs"] # Chec ...

Finding a specific item within a webpage

I am having trouble locating an element on a webpage, and I suspect frames or iframes may be causing the issue. Despite trying xpath and other criteria, I keep receiving a "No such element" message. The webpage in question can be found at . After attempti ...

Check to see if a dictionary is nested within another dictionary

Exploring how to compare Python dictionaries for equality: first = {"one":"un", "two":"deux", "three":"trois"} second = {"one":"un", "two":"deux", "three":"trois"} print(first == second) # Output: True Now, what if the second dictionary has extra keys ...

Provide a varying quantity of entities for each return

Here is the function I am currently working with: def foo(): try: a = bar1() b = bar2() except Exception as e: logging.exception(e) return return a, b It's worth noting that this function may return differ ...

I'm looking to duplicate a variety of files scattered across several folders

For example, I have sam1_1.gz, sam2_1.gz, sam3_1.gz, and 200 more files like these. Each file has a corresponding folder named sam1, sam2, sam3, etc. I want to copy sam1.gz to /home/users/sam1, sam2.gz to /home/users/sam2, and so forth. Additionally, I n ...

Retrieve Associated Key in Django and Add to Database

Hey there, I'm working on a feature that allows users to add a "product" to their shop without the need to select a shop since each user will have only one shop. I'm encountering an error message: "IntegrityError at /shop/product/add/ NOT NULL ...

How can I release a pyarmor encrypted Python package that is compatible with all python versions?

Seeking guidance on releasing a customized python package, I am utilizing the pyarmor tool for obfuscation before submitting it to PyPi. While it performs well within the same python version environment, according to the documentation here: packaging-obfus ...