1

I have a tkinker window with date and choose date button which i call it as a home page. When the user choose the date, I want the date to be updated in the Home Page. I retuned the selected date in the datecheck function. Then i want to update the homepage date with returned date. I don't know how to make it possible. Help me with some solution.

Here's the Sample Code I wrote:

from tkinter import *
from tkinter import ttk
from tkinter import scrolledtext
import time
import tkinter.messagebox
from datetime import datetime
import tkinter as tk
import sys
import os
from tkcalendar import Calendar, DateEntry
from datetime import date
import multiprocessing


def datecheck():
    global date_string
    root = Tk()
    s = ttk.Style(root)
    s.theme_use('clam')
    def print_sel():
        global date_string,timestamp
        date_string =cal.selection_get()
        date_string=date_string.strftime("%d-%b-%Y")
        print("returned_date",date_string)
        root.destroy()
    today = date.today()
    d = int(today.strftime("%d"))
    m= int(today.strftime("%m"))
    y =int(today.strftime("%Y"))
    cal = Calendar(root,
                   font="Arial 14", selectmode='day',
                   cursor="hand1",   day=d,month=m,year=y)
    cal.pack(fill="both", expand=True)
    ttk.Button(root, text="ok", command=print_sel).pack()
def homepage():
    global date_string,timestamp
    if date_string == "":
            timestamp = datetime.now().strftime("%d-%b-%Y")

    else:
        timestamp = date_string
    def close_window():
        window.destroy()

    window = Tk()
    window.title("Status Uploader")
    window.geometry('500x200')
    Label(window,
          text="Status Uploader",
          fg="blue",
          bg="yellow",
          font="Verdana 10 bold").pack()
    Label(window,
          text="Date : {}".format(timestamp),
          fg="red",
          bg="yellow",
          font="Verdana 10 bold").pack()

    txt = scrolledtext.ScrolledText(window, width=60, height=9.5)
    txt.pack()
    button = Button(window, fg='white', bg='blue',
                    text="Choose Date", command=datecheck)
    button.place(x=35, y=152)
    button = Button(window, fg='white', bg='red',
                    text="Close", command=close_window)
    button.place(x=405, y=152)
    window.mainloop()        

global date_string,timestamp
date_string = ""
homepage()

Screenshot:

screenshot of script running

  • What have you done to debug this? Have you verified that the other process starts? Have you verified that you're actually changing `datestring`? Are you aware that simply changing `timestamp` won't change anything on the display? – Bryan Oakley Sep 27 '19 at 19:03
  • Yes, the common way to do other things while `tkinter`'s `mainloop()` is running (which _must_ be called so the GUI can process user events) is to use the universal widget [`after()`](https://web.archive.org/web/20190222214221id_/http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/universal.html) method to schedule periodic calls to a function. – martineau Sep 27 '19 at 19:06
  • @Bryan Oakley, Yes the two process gets started. – crust salty Sep 27 '19 at 19:10
  • @crustsalty: Remove all `multiprocessing` related stuff and follow this pattern [python calendar widget - return the user-selected date](https://stackoverflow.com/a/27774216/7414759) – stovfl Sep 27 '19 at 19:11
  • @Bryan Oakley, I have removed mutiprocessing and returned the date. I have updated the code. After that, how to update the `homepage date` with my `returned_date` – crust salty Sep 27 '19 at 19:18
  • @crustsalty: Do you realy need a own window `datecheck()`? You have **two** `= Tk()` you should only have **one**. Rarad [Why are multiple instances of Tk discouraged?](https://stackoverflow.com/questions/48045401/why-are-multiple-instances-of-tk-discouraged) – stovfl Sep 27 '19 at 19:27

1 Answers1

1

Here's a version of your code that doesn't use multiprocessing because I don't think its use is necessary — although I don't really understand what you're trying to do with respect to the two date_string and timestamp global variables and how they relate to one another. All that happens in the code below is the latter is copied to the first periodically by the fun() function which is called every 1000 millisecs (e.g. once per second).

That is done by using the universal tkinter widget after{} method to periodically check the date and time and update the global variables — something multiprocessing isn't required to be able to do in this case.

To get the Label showing the date to change after the user has chose a new date, I've added a date_label parameter to datecheck() function and modified the homepage() function to pass it as an argument to the function when it's called by clicking on the Choose Date Button.

I also generally cleaned up the code and made it follow the PEP 8 - Style Guide for Python Code guidelines to make it easier to read and maintain.

from datetime import date, datetime
from functools import partial
import os
import sys
from tkcalendar import Calendar, DateEntry
from tkinter import ttk
from tkinter import scrolledtext
import tkinter as tk

def datecheck(date_label):
    global date_string, timestamp

    root = tk.Toplevel()
    s = ttk.Style(root)
    s.theme_use('clam')

    def print_sel():
        global date_string

        cal_selection = cal.selection_get()
        date_string = cal_selection.strftime("%d-%b-%Y")
        # Update the text on the date label.
        date_label.configure(text="Date : {}".format(date_string))
        root.destroy()

    today = date.today()
    d = int(today.strftime("%d"))
    m = int(today.strftime("%m"))
    y =int(today.strftime("%Y"))

    cal = Calendar(root,
                   font="Arial 14", selectmode='day',
                   cursor="hand1", day=d,month=m, year=y)
    cal.pack(fill="both", expand=True)

    ttk.Button(root, text="ok", command=print_sel).pack()


def homepage():
    global date_string, timestamp

    if date_string == "":
        timestamp = datetime.now().strftime("%d-%b-%Y")
    else:
        timestamp = date_string

    def close_window():
        window.destroy()

    window = tk.Tk()
    window.title("Status Uploader")
    window.geometry('500x200')
    tk.Label(window,
             text="Status Uploader",
             fg="blue",
             bg="yellow",
             font="Verdana 10 bold").pack()
    date_label = tk.Label(window,
                          text="Date : {}".format(timestamp),
                          fg="red",
                          bg="yellow",
                          font="Verdana 10 bold")
    date_label.pack()

    # Create callback function for "Choose Date" Button with data_label
    # positional argument automatically supplied to datecheck() function.
    datecheck_callback = partial(datecheck, date_label)

    txt = scrolledtext.ScrolledText(window, width=60, height=9.5)
    txt.pack()

    button = tk.Button(window, fg='white', bg='blue',
                       text="Choose Date",
                       command=datecheck_callback)
    button.place(x=35, y=152)
    button = tk.Button(window, fg='white', bg='red', text="Close", command=close_window)
    button.place(x=405, y=152)

    window.after(1000, fun, window)  # Start periodic global variable updates.
    window.mainloop()


def fun(window):
    """ Updates some global time and date variables. """
    global date_string, timestamp

    if date_string == "":
        timestamp = datetime.now().strftime("%d-%b-%Y")
    else:
        timestamp = date_string

    window.after(1000, fun, window)  # Check again in 1000 milliseconds.


# Define globals.
date_string = ""
timestamp = None

homepage() # Run GUI application.
martineau
  • 119,623
  • 25
  • 170
  • 301
  • crust salty: Glad to hear it helped. Programming `tkinter` can be rather difficult because it's so poorly documented and isn't "pythonic" in many respects, plus it has a lot of "rules" and a certain number of "tricks" need to be learned to make the best use of it — so it might not be the quickest way of learning the basics of the Python language. Regardless, having some that works like this now does to play with should go a long way in mastering it. Best of luck on your endeavor. – martineau Sep 28 '19 at 07:19