2016-11-18 68 views
0

所以我试图每次用户点击一个按钮时添加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

问题是因为'Button'执行函数,但它不能接收返回值,所以你不能分析'curdate'返回的值。你可以把所有的东西放在一个班上,并使用'self.'。 – furas

+0

顺便说一句,你的python 3的语法是错误的。这个代码将不会在python 3上执行。 – Lafexlos

回答

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() 
+0

谢谢,那可行,但是按钮将不得不更新来自不同对象的更多变量......所以将所有内容放在一个大类中可能会很麻烦...... – Gobhniu

+0

这是为什么你使用面向对象的编程。 App类可以包含其他类的实例。例如,您可能有一个类存储日期,一个存储人员列表,另一个存储清单。你甚至可以有一个类的实例列表。然后,App类可以在按下按钮时调用每个类的更新方法。这样做比在整个代码中随机变量要好得多。分组类似的变量以及将它们修改为类的方法。 – scotty3785

+0

非常感谢 – Gobhniu