2012-03-31 97 views
0

我試圖做一些包裝/類的製作,使tkinter GUI更簡單。我意識到這是多餘的,它不會使代碼更漂亮或更小,但我只是想嘗試,如果我能做到這一點。這是我的代碼。Python自定義tkinter gui類/包裝函數不適用於每個實例。

#!/usr/bin/env 
from tkinter import * 
import tkinter.messagebox 

class Bysic(): 
def __init__(self): 
    self.app = Tk() 

def createButton(self, label, row, col, command, sticky=W): 
    self.button = Button(self.app,text=label,command=command) 
    self.button.grid(row=row, column=col, sticky=sticky) 

def setSize(self, width, height): 
    self.app.geometry(str(width)+"x"+str(height)) 

def setTitle(self, title): 
    self.app.title(title) 

def createEntry(self, caption, row, col, width=None, defaultValue=None, alignment=W, **options): 
    self.entryLabel = Label(self.app, text=caption) 
    self.entryLabel.grid(row=row, column=col, sticky=W) 
    self.entry = Entry(self.app, **options) 
    if defaultValue: 
     self.entry.delete(0, END) 
     self.entry.insert(0, defaultValue) 
    if width: 
     self.entry.config(width=width) 
    self.entry.grid(row=row, column=col+1, sticky=W) 
    return self.entry 

def createLabelVar(self, caption, row, col, alignment=W): 
    self.labelVar = StringVar() 
    self.labelVar.set(caption) 
    self.label = Label(self.app, textvar=self.labelVar) 
    self.label.grid(row=row, column=col, sticky=alignment) 
    return self.labelVar 

def createLabel(self, caption, row, col, alignment=W): 
    self.staticLabel = Label(self.app, text=caption) 
    self.staticLabel.grid(row=row, column=col, sticky=alignment) 

def appLoop(self): 
    self.app.mainloop() 

def appKill(self): 
    self.app.destroy() 

我現在可以實例化一個'Bysic'對象並在其上生成GUI元素。然而,只有一個元素,createLabelVar只能在第一個gui上工作。讓我來證明一下。

import bysic 
x = Bysic() 
label = x.createLabelVar("Original text",0,0) 
label.set("Overriding text") 

a = Bysic() 
newLabel = a.createLabelVar("Original text",0,0) 
newLabel.set("Override") 

第一Bysic實例(X)確實顯示文本「重寫文本」,然而第二Bysic實例標籤(a)不顯示任何東西,只是一個空的Tkinter窗口。

怎麼回事?我的意思是,x和a是分開的,爲什麼createLabelVar函數只能處理一個實例而不能處理另一個實例?

在此先感謝!

回答

0

Tkinter沒有被設計爲具有Tk類的多個實例。您只能創建一個,並且只能運行一個mainloop

如果你想要多個窗口,你需要創建Toplevel的實例。

相關問題