Home > Back-end >  How do I store a variable in a function so I can access it from a different file
How do I store a variable in a function so I can access it from a different file

Time:12-05

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.

CodePudding user response:

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

CodePudding user response:

a = 5

def set_a(val):
    global a
    a = val
    
print(a)
set_a(0)
print(a)

What you are doing is a very bad practice (you can use the global keyword before your variable to update it, but never do this). Instead either store it in a mutable data object for example a dictionary or as a pickle file(depending on your application).

program_variables = {'a':5}

def set_a(val):
    program_variables['a'] = val
    
print(program_variables['a'])
set_a(0)
print(program_variables['a'])

if you need pickles, you can search for tutorials on using it as well

  • Related