Reputation: 275
So I am trying to add 7 days to a date everytime the user clicks on a button. Here is a simplified version of my code:
import sys
if sys.version_info[0] == 2: # Just checking your Python version to import Tkinter properly.
import Tkinter as tk
import ttk as ttk
else:
import tkinter as tk
from tkinter.ttk import ttk as ttk
import datetime
import calendar
def nextweek(cd, ow):
newdate=(cd+ow)
cd=newdate
return cd
def printdate(cd):
print cd
curdate = datetime.date(2016, 01, 04)
one_week = datetime.timedelta(weeks = 1)
root = tk.Tk()
bls = ttk.Style()
bls.configure('Black.TLabelframe', background="#222222")
dayframe = ttk.Button(root, text="Hello", command=lambda: nextweek(curdate, one_week))
dayframe.grid(row=1, column=1, padx=5)
dayframetest = ttk.Button(root, text="test", command=lambda: printdate(curdate))
dayframetest.grid(row=2, column=1, padx=5)
root.mainloop()
All the examples I saw so far use global variables, is there a way to do it without making curdate a global?
Upvotes: 0
Views: 71
Reputation: 7006
It is generally better to use an Object Oriented approach to creating tkinter applications. I've taken your example and modified it so that the curdate is stored inside the App class.
N.B. I tested it on python3.
import sys
if sys.version_info[0] == 2: # Just checking your Python version to import Tkinter properly.
import Tkinter as tk
import ttk as ttk
else:
import tkinter as tk
import tkinter.ttk as ttk
import datetime
import calendar
class App(tk.Frame):
def __init__(self,master=None,**kw):
tk.Frame.__init__(self,master=master,**kw)
bls = ttk.Style()
bls.configure('Black.TLabelframe', background="#222222")
self.dayframe = ttk.Button(self, text="Hello", command= self.nextweek)
self.dayframe.grid(row=1, column=1, padx=5)
self.dayframetest = ttk.Button(self, text="test", command= self.printdate)
self.dayframetest.grid(row=2, column=1, padx=5)
self.curdate = datetime.date(2016, 1, 4)
self.one_week = datetime.timedelta(weeks = 1)
def nextweek(self):
self.curdate = (self.curdate + self.one_week)
def printdate(self):
print(self.curdate)
if __name__ == '__main__':
root = tk.Tk()
App(root).grid()
root.mainloop()
Upvotes: 2