2013-07-11 22 views
2

我有Tkinter的關於兩個模塊分離UI和UI功能的問題,這裏是我的代碼:如何在python tkinter中分離視圖和控制器?

1-view.py

from tkinter import * 

class View(): 
    def __init__(self,parent): 
     self.button=Button(parent,text='click me').pack() 

2.controller.py

from tkinter import * 
from view import * 

class Controller: 
    def __init__(self,parent): 
     self.view1=View(parent) 
     self.view1.button.config(command=self.callback) 

    def callback(self): 
     print('Hello World!') 


root=Tk() 
app=Controller(root) 
root.mainloop() 

on running controller.py我得到以下錯誤:

AttributeError:'NoneType'對象沒有attri bute'config'

有什麼建議嗎?

此外,我試圖使用lambda在另一個模塊中使用回調函數,但它沒有工作。

在此先感謝

回答

1

在view.py您致電:

self.button=Button(parent,text='click me').pack()

pack功能不返回要分配給self.button Button對象,這會導致AttributeError稍後。你應該這樣做:

self.button = Button(parent, text='click me') 
self.button.pack() 
+0

非常感謝Paulo的幫助。 最好的問候 – Mehdi

2

lambda方法的問題和上面的一樣,現在通過在一個新行中使用pack來解決。看起來更漂亮,這裏是使用lambda這是工作的罰款樣本:

1.view.py

from tkinter import * 
from controller import * 

class View(): 
    def __init__(self,parent): 
     button=Button(parent,text='click me') 
     button.config(command=lambda : callback(button)) 
     button.pack() 


root=Tk() 
app=View(root) 
root.mainloop() 

2.controller.py

def callback(button): 
    button.config(text='you clicked me!') 
    print('Hello World!') 

使用這種方法,我們可以移動所有功能遠離UI,並使其清晰可讀。

相關問題