使用新内容python创建新框架

时间:2016-01-24 15:44:35

标签: python tkinter

如何创建新框架并通过pyhton将值传递给它?

代码:

 import Tkinter as tk
 import tkMessageBox
 import json
 import requests
 from urllib import urlopen
 import os.path
 import threading

类myapp(tk.Frame):

def callfunc(self,title = "", author = "", body = ""):
    tk.Frame.__init__(self, top)
    self.canvas = tk.Canvas(top, borderwidth=0, background="#ffffff")
    self.frame = tk.Frame(self.canvas, background="#ffffff")
    self.vsb = tk.Scrollbar(top, orient="vertical", command=self.canvas.yview)
    self.canvas.configure(yscrollcommand=self.vsb.set)

    self.vsb.pack(side="right", fill="y")
    self.canvas.pack(side="left", fill="both", expand=True)
    self.canvas.create_window((4,4), window=self.frame, anchor="nw", 
                              tags="self.frame")

    self.frame.bind("<Configure>", self.onFrameConfigure)
    print title
    data_json = ""
    L1 = tk.Label(self, text="Title")
    L1.pack()
    E1 = tk.Entry(self, bd =5)
    E1.pack()
    #E1.insert(0,title)

    L2 = tk.Label(self, text="Author")
    L2.pack( )
    E2 = tk.Entry(self, bd =5)
    E2.pack()
    #E2.insert(0,author)

    L3 = tk.Label(self, text="Body")
    L3.pack( )
    E3 = tk.Entry(self, bd =5)
    E3.pack()
    #E3.insert(0,body)
    if (title !=""):
        data = {"author": E2.get(),
        "body" : E3.get(),
        "title" : E1.get()}
        data_json = json.dumps(data)
    self.SubmitButton = tk.Button(self,text="Submit", fg="White", bg="#0094FF", 
                                font=("Grobold", 10), command = lambda: self.submitfunc(data_json))
    self.SubmitButton.pack()
    #SubmitButton.pack()

def submitfunc(self,data_json):
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    url = 'http://localhost/spritle/api.php?action=insert_list&data_json='
    check = self.connected_to_internet(url)
    if(check):
        r = requests.post(url+data_json ,headers=headers )
        print r.status_code
        # if (r.status_code == 200):
        #     tkMessageBox.showinfo("Result","success")
        # else:
        #     if(os.path.isfile("offline_post.json")):
        #         with open('offline_post.json','a') as f:
        #             f.write(data_json+"\n")
        #     else:
        #         open('offline_post.json', 'a')
        #         with open('offline_post.json','a') as f:
        #             f.write(data_json+"\n")

# homeButton = Button(text="Home", fg="White", bg="#0094FF", 
#                               font=("Grobold", 10), command = view)
# homeButton.pack()

def connected_to_internet(self,url, timeout=5):
    try:
        _ = requests.get(url, timeout=timeout)
        #threading.Timer(10, connected_to_internet(url)).start()
        #print "asd"
        return True
    except requests.ConnectionError:
        print("No internet connection available.")
        return False

def onFrameConfigure(self,event):
    self.canvas.configure(scrollregion=self.canvas.bbox("all"))


def __init__(self, parent):        
    self.home()

def home(self):
    tk.Frame.__init__(self, top)
    self.canvas = tk.Canvas(top, borderwidth=0, background="#ffffff")
    self.frame = tk.Frame(self.canvas, background="#ffffff")
    self.vsb = tk.Scrollbar(top, orient="vertical", command=self.canvas.yview)
    self.canvas.configure(yscrollcommand=self.vsb.set)

    self.vsb.pack(side="right", fill="y")
    self.canvas.pack(side="left", fill="both", expand=True)
    self.canvas.create_window((4,4), window=self.frame, anchor="nw", 
                              tags="self.frame")

    self.frame.bind("<Configure>", self.onFrameConfigure)
    self.row=0
    # url = "http://localhost/spritle/api.php?action=get_users";
    # r = requests.get(url)
    # j = r.json()
    E1 = tk.Label(self.frame, text="Title")
    E1.grid(row=self.row, column=0)
    E1 = tk.Label(self.frame, text="Author")
    E1.grid(row=self.row, column=1)
    E1 = tk.Label(self.frame, text="Body")
    E1.grid(row=self.row, column=2)
    j = [[0 for x in range(5)] for x in range(5)] 
    # j[0]['title'] = "asdg"
    # j[0]['author'] = "asdg"
    # j[0]['body'] = "asdg"
    print j
    for val in j:
        self.row += 1
        T1 = tk.Label(self.frame, text=val)
        T1.grid(row=self.row, column=0)
        A1 = tk.Label(self.frame, text=val)
        A1.grid(row=self.row, column=1)
        B1 = tk.Label(self.frame, text=val)
        B1.grid(row=self.row, column=2)
        editButton = tk.Button(self.frame, text="Edit", fg="White", bg="#0094FF", 
                                 font=("Grobold", 10),command = lambda title=val,author=val,body=val: self.callfunc(title,author,body))
        editButton.grid(row=self.row,column=3)
    #     editButton.pack()
    newButton = tk.Button(self.frame, text="New Post", fg="White", bg="#0094FF",
                                 font=("Grobold", 10),command =  lambda:self.callfunc)
    newButton.grid(row = self.row + 1, column = 2)

 top = tk.Tk()
 top.title("App")
 sizex = 400
 sizey = 300
 posx  = 50
 posy  = 50
 top.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))
 app = myapp(top)
 top.mainloop()

我是新的GUI程序员。有办法吗?或者我可以覆盖旧框架本身吗? 尝试相同的框架,但内容没有覆盖它显示每一件事....

1 个答案:

答案 0 :(得分:1)

我认为你可能会混淆Frames with Toplevels(windows)一个Frame只是一个通用的容器,当没有给出父级时会产生一个自己的窗口但是要创建新窗口你需要创建一个Toplevel小部件:< / p>

class EXAMPLE_APP(tk.Frame):
    def __init__(self,master=None):
        tk.Frame.__init__(self,master)
        self.master.title("still a master")

        self.windows = []
        self.new_button = tk.Button(self,text="make a new window",command=self.new_window)
        self.new_button.grid()
        self.del_button = tk.Button(self,text="delete a window",command=self.del_window)
        self.del_button.grid()

    def new_window(self,event=None):
        new = tk.Toplevel(self)
        new.title("window %d"%len(self.windows))
        tmp_label = tk.Label(new,text="here is the label")
        tmp_label.grid() 
        #it is only temporary because reference is lost when the function finishes, it would be much preferable to have a separate class
        self.windows.append(new)

    def del_window(self,event=None):
        self.windows.pop().destroy()

app = EXAMPLE_APP() #note that you don't have to explicitly specify a root
app.grid() #still have to grid the Frame to its master

app.mainloop()

如果新窗口需要有东西(当然它有!)那么你可以考虑为弹出窗口创建一个类:

class Popup(tk.Toplevel):
    def __init__(self,tk_master,title=None,author=None,body=None):
        #most of this code is from your callfunc() method, just changed what is master to widgets
        tk.Toplevel.__init__(self,tk_master)
        if title:
            self.title(title)
        self.canvas = tk.Canvas(self, borderwidth=0, background="#ffffff")
        self.frame = tk.Frame(self.canvas, background="#ffffff")
        ...

    def onFrameConfigure(self,event):
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))



class myapp(tk.Frame):
    def callfunc(self,title = "", author = "", body = ""):
        popup = Popup(self.parent,title,author,body)

    ...

    def __init__(self, parent):
        self.parent  = parent
        self.home()

    def home(self):
        tk.Frame.__init__(self, self.parent) #wouldn't this make more sense in __init__?
        ...