如何使用类链接tkinter gui和程序?

时间:2014-07-22 09:59:11

标签: class python-2.7 tkinter

我对python类和tkinter有很多疑问。 我之前从未使用过,但我正在尝试制作我的第一个程序并将其链接到gui。 我分别做了我的程序和我的gui,这是一个糟糕的选择?

我的第一部分代码是:

from datetime import datetime
class MyProgram:

#dictonary with the information
    d={1: ('sun','Paris',datetime(2012,4,17,00,00)), 2: ('cloud','Londres',datetime(2012,6,24,00,00)), 3 :  ('snow','NewYork',datetime(2012,8,8,00,00)),4 : ('sun','Tokyo',datetime(2012,11,30,00,00))}
#List of string of d
    d_string=[('sun','Paris',str(datetime(2012,4,17,00,00))),('cloud','Londres',str(datetime(2012,6,24,00,00))),('snow','NewYork',str(datetime(2012,8,8,00,00))),('sun','Tokyo',str(datetime(2012,11,30,00,00)))]    

#function to query d
    def queryD(timeAfter=datetime(1900,01,01,00,00), timeBefore=datetime(2500,01,01,00,00),place=None):

        if place == None:    
            answer = [[key,values] for key,values in MyProgram.d.items() if values[2]>timeAfter and values[2]<timeBefore]

        else:
            answer = [[key,values] for key,values in MyProgram.d.items() if values[2]>timeAfter and values[2]<timeBefore and values[1]==place]
        return answer     

#function to write the results of queryD not finished yet because i can just print d_string, but it is not the queastion  
    def writeIndex():

    #open index.txt and give the right to write    
            myFile=open('output.txt', 'w')     
            for l in MyProgram.d_string:  
                myFile.writelines('\t'.join(l)+'\n')  
            myFile.close()
            return myFile

#function to read the file output        
    def readIndex():

    #open index.txt and give the right to read
            with open('output.txt', 'r') as f:
    #return all the written informations in index.txt in a terminal
                return [myIndex.split('\t') for myIndex in f.readlines()]

我的GUI是:

from Tkinter import *
from datetime import * 
import MyProgram

class App:

    def __init__(self, gui):

        gui = Frame(gui)
        gui.grid()

#AFTER      

     #Create Text
        self.textAfter = Label(gui, text="Put a date : ")
       #give to Text a place 
        self.textAfter.grid(column=0,row=0)

       #Create an area to write text
        self.entryAfter = Entry(gui)        
        self.entryAfter.grid(column=1,row=0,sticky='EW')
        self.entryAfter.insert(0, 'YYYY/MM/DD')

        self.entryAfter.focus_set()

       #Create a button 
        self.buttonAfter = Button(gui,text=u'After', command=self.getAfterTxT)
        self.buttonAfter.grid(column=2,row=0)                   

#BEFORE      
        self.textBefore = Label(gui, text="Put a date : ")
        self.textBefore.grid(column=0,row=1)

        self.entryBefore = Entry(gui)        
        self.entryBefore.grid(column=1,row=1,sticky='EW')
        self.entryBefore.insert(0, 'YYYY/MM/DD')

        self.buttonBefore = Button(gui,text=u"Before",command=self.getBeforeTxT)
        self.buttonBefore.grid(column=2,row=1) 

#PLACE      
        self.textStation = Label(gui, text="Select your place : ")
        self.textStation.grid(column=0,row=2)

        self.optionList = ('Paris', 'Tokyo', 'Londres','NewYork')
        self.var = StringVar(gui)
        self.optionmenu = apply(OptionMenu, (gui,self.var) + tuple(self.optionList))
        self.optionmenu.grid(column=1, row=2,sticky="WE")

        self.buttonStation = Button(gui,text=u"Place", command = self.getPlaceValue)
        self.buttonStation.grid(column=2,row=2)

#QUIT
        self.bouttonQuit = Button(gui, text='Quit', command = gui.quit)
        self.bouttonQuit.grid(column=2,row=3)

#SAVE AS 
        self.buttonSaveAs = Button(gui,text=u"Save As", command = self.printData)
        self.buttonSaveAs.grid(column=1,row=3)  

#get the text from the emtry entryAfter       
#I don't know how i can use afterTxTd,beforeTxTd,stationPlace in MyProgram
#to put in my function queryD
    def getAfterTxT(self):
        afterTxT = self.entryAfter.get()
        afterTxTd=datetime.strptime(afterTxT,'%Y/%m/%d')

    def getBeforeTxT(self):
        beforeTxT = self.entryBefore.get()
        beforeTxTd= datetime.strptime(beforeTxT,'%Y/%m/%d')

    def getPlaceValue(self):
        stationPlace = self.var.get()        

#This is the error
    def printData(self):
        MyProgram.writeIndex()

gui = Tk()

app = App(gui)

gui.mainloop()
gui.destroy()

当用户点击按钮后(在输入日期之后),我想运行MyProgram,运行脚本,在文本文件中写入信息并使用函数readIndex()显示结果。 之后,如果用户想要保存文件,他只需按“另存为”按钮即可。 你有什么建议可以帮助我吗?任何教程?我是否必须为MyProgram中的每个函数创建一个类,我是否必须为每个类创建一个“ init ”? Thanx阅读这篇文章!祝你今天愉快 !

1 个答案:

答案 0 :(得分:1)

如果您在文件myfirst_script.py中有第一个脚本,则将其导入为

import myfirst_script 

然后您可以将其用作

my_program = myfirst_script.MyProgram()
my_program.writeIndex()

如果您在文件MyProgram.py中有第一个脚本,则将其导入为

import MyProgram

然后您可以将其用作

my_program = MyProgram.MyProgram()
my_program.writeIndex()

或者您可以导入为

from MyProgram import MyProgram

然后您可以将其用作

my_program = MyProgram()
my_program.writeIndex()

BTW:类中的所有函数都需要self作为第一个参数,因为调用

my_program.writeIndex()

(内部用于python)几乎就像调用

一样
writeIndex(my_program)

顺便说一句:类在代码中生成顺序,但我认为你不需要类MyProgram,你可以在第一个脚本中只使用分离的函数。

然后你可以使用它(没有所有self s)

import myfirst_script 

myfirst_script.writeIndex() 

最终,在globald中更改值的某些函数中需要d_string