Search code examples
pythontkintertkcalendar

How do I store a variable in a function so I can access it from a different file


I am trying to make a program that allows you to select a day, and then store a value for the day with a separate file. However, I can't find a way to store the selected day in a variable that I can use.

from tkinter import *
from tkcalendar import *

main = Tk()
main.title('Calendar')
main.geometry('600x400')

cal = Calendar(main, selectmode='day')
cal.pack()


def set_date():
    my_label.config(text=cal.get_date())
    today = cal.get_date()
    print(today)


my_button = Button(main, text='Get Date',command=set_date)
my_button.pack(pady=20)

my_label = Label(main,text="Haha")
my_label.pack(pady=20)

main.mainloop()

If I store the vairable inside the function set_date() it stores the date that is selected but I can't import it on a separate file. And if I store the variable outside of the function set_date() it only stores the current date and not the one selected.


Solution

  • I can't tell exactly what you want because of how you worded it, but I'm pretty sure this is what you want

    def set_date():
        my_label.config(text=cal.get_date())
        today = cal.get_date()
        return today
    

    If you then import this function in another file and call it like this

    selected_date = set_date()
    

    This isn't quite what you want though as it will modify the label each time you want to get the date, so you will want to add this function to get the selected date that you want.

    def get_date():
        today = cal.get_date()
        return today