因此,每次用户点击按钮时,我都会尝试将7天添加到日期中。 这是我的代码的简化版本:
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()
到目前为止我看到的所有例子都使用全局变量,有没有办法在不使curdate成为全局变量的情况下做到这一点?
答案 0 :(得分:2)
通常最好使用面向对象的方法来创建tkinter应用程序。我已经对你的例子进行了修改,以便将curdate存储在App类中。
N.B。我在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()