Is there an option to use user input besides print it in Python

106 Views Asked by At

First off, I am new to Python and new to programming. but I am trying to make a program that puts together a database with user input. In this particular example, I am trying to take a date from user input and add it to a dataclass

here is the relevant code.

import tkinter as tk
from tkinter import ttk

import tkcalendar
from tkcalendar import Calendar, DateEntry

window = tk.Tk()
window.title("Route Cards")

def enter_data():
    date = date_entry.get()
    print(date)

def date_entry ():
    def print_sel():
        print(cal.selection_get())

top = tk.Toplevel(window)

    cal = Calendar(top, font="Arial 14", selectmode='day',             locale='en_US',
                   cursor="hand1", year=2024, month=1, day=26)

    cal.pack(fill="both", expand=True)
    ttk.Button(top, text="ok", command=print_sel).pack()

date = ttk.Button(customer_info_frame, text='date', command=cal_select)
date.grid(row=7, column=1)

window.mainloop()

the date box opens a window and when the user selects the date and chooses ok it prints. but I want to take that date and add it to the function enter_data so I can add it to a dataclass as a str (or a datetime)

but all I can do is print it in the terminal. I have tried Return but it just returns "None"

The answer to this particular problem would be helpful but i just need help in general on how to get a user input() and put that information elsewhere. Thank you in advance!

EDIT: I got this particular code to work with quite a bit of re writing, but the main question stands. Maybe the problem I am having is with taking input from a function and using it? Like I said, I am new, so I'm not really sure what the problem is. But is there a way to take a string from input from one function and use it in another function?

1

There are 1 best solutions below

0
8349697 On BEST ANSWER

In your case, the most common solutions are: passing the values of local variables using a lambda or using a global textvariable.

See also: How to pass arguments to a Button command in Tkinter


Using a lambda to get a value from an input field.

import datetime
import tkinter as tk
import tkinter.ttk as ttk

from tkcalendar import Calendar


def enter_data():
    print("Enter data:")
    try:
        datetime_obj = datetime.datetime.strptime(date_entry.get(), "%m/%d/%Y")
        print(datetime_obj)
        print("entry value:", date_entry.get())
    except ValueError:
        print("Invalid date")

    
def get_locals(top_widget, cal_value, formated_date):
    """
    top_widget: <class 'tkinter.Toplevel'>
    cal_value:  <class 'datetime.date'>
    formated_date: <class 'str'>
    """
    date_entry.delete(0, "end")
    date_entry.insert(0, formated_date) 
    top_widget.withdraw()
    print("Get locals:", "\ncal_value:", cal_value, "\nformated_date:", formated_date)

    
def demo(text):
    top = tk.Toplevel(window, name="top") # one at a time
    x = window.winfo_x()
    y = window.winfo_y() 
    top.geometry(f"+{x + 100}+{y + 100}")
    top.title(text)
    cal = Calendar(top, font="Arial 14", selectmode='day',
                   locale='en_US', cursor="hand1",
                   date_pattern="mm/dd/yyyy")
    cal.pack(fill="both", expand=True)
    # using a lambda to delay the execution of a function until a button is clicked
    # pass locals to another function
    top_button = ttk.Button(top, text="ok",
                            command=lambda: get_locals(top, cal.selection_get(), cal.get_date()))
    top_button.pack()
    print("Demo locals:\n", locals().keys())

    
window = tk.Tk()
window.title("Route Cards")

date_entry = ttk.Entry(window)
date_entry.pack()
date_entry.insert(0, "01/30/2024")
                  
demo_button = ttk.Button(window, text="Demo", command=lambda: demo("Calendar"))
demo_button.pack()

submit_button = ttk.Button(window, text="Submit form", command=enter_data)
submit_button.pack()

# these names are available in functions
print("Globals:")
print(globals().keys())

window.mainloop()

Using a textvariable to get or set the value of an input field.

import datetime
import tkinter as tk
import tkinter.ttk as ttk

from tkcalendar import Calendar


def enter_data():
    print("Enter data:")
    print("textvariable:", date_textvariable.get())
    try:
        datetime_obj = datetime.datetime.strptime(date_entry.get(), "%m/%d/%Y")
        print(datetime_obj)
        print("entry value:", date_entry.get())
    except ValueError:
        print("Invalid date")

    
def demo(text):
    top = tk.Toplevel(window, name="top") # one at a time
    x = window.winfo_x()
    y = window.winfo_y() 
    top.geometry(f"+{x + 100}+{y + 100}")
    top.title(text)
    cal = Calendar(top, font="Arial 14", selectmode='day',
                   locale='en_US', cursor="hand1",
                   date_pattern="mm/dd/yyyy")
    cal.pack(fill="both", expand=True)
    # change entry value
    top_button = ttk.Button(top, text="ok",
                            command=lambda: [date_textvariable.set(cal.get_date()), top.withdraw()])
    top_button.pack()

    
window = tk.Tk()
window.title("Route Cards")

date_textvariable = tk.StringVar()
print("empty:", date_textvariable.get())
date_textvariable.set("01/30/2024")
print("initial value:", date_textvariable.get())

date_entry = ttk.Entry(window, textvariable=date_textvariable)
date_entry.pack()

demo_button = ttk.Button(window, text="Demo", command=lambda: demo("Calendar"))
demo_button.pack()

submit_button = ttk.Button(window, text="Submit form", command=enter_data)
submit_button.pack()

# these names are available in functions
print("Globals:")
print(globals().keys())

window.mainloop()

print("Var:", date_textvariable.get())