我已經看到了使用Tkinter製作基本窗口的兩個不同教程。其中一個教程使用具有函數的類來初始化和組裝窗口。在另一個教程中,他們只是在不使用類或函數的情況下創建了一個窗口。在tkinter中製作窗口的哪種方式比較好?
只是要清楚,我不是在說什麼窗戶本身。我只是想知道哪種方法更好地實施Tkinter。
如果解釋沒有意義,這裏是兩者的代碼。
如果解釋沒有意義,這裏是兩者的代碼。
CODE#1使用類
from tkinter import *
class Window(Frame):
def __init__(self, master=NONE):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.master.title("GUI") #
self.pack(fill = BOTH, expand=1)
# We created a button below to see how to do it but commented it out for now.
'''closeButton = Button(self, text='Close', command=self.client_exit) # Making a new button called closeButton.
closeButton.place(x=0, y=0) # Places the button at given co-ordinates. (0,0) is top left. This isn't cartesian.'''
menuBar = Menu(self.master)
self.master.config(menu=menuBar)
file = Menu(menuBar)
file.add_command(label = 'Exit', command = self.client_exit)
menuBar.add_cascade(label = 'File', menu=file)
edit = Menu(menuBar)
edit.add_command(label = 'Show Image', command = self.showImg)
edit.add_command(label = 'Show Text', command = self.showTxt)
menuBar.add_cascade(label = 'Edit', menu=edit)
def showImg(self):
load = Image.open('CatPic.jpg')
render = ImageTk.PhotoImage(load)
catImage = Label(self, image=render)
catImage.image = render
catImage.place(x=250, y=250)
def showTxt(self):
writeText = Label(self, text = "Hi I'm Temmie")
writeText.pack()
root = Tk() # Tk() is a function within Tkinter. 'root' is the name of our Frame.
root.geometry("500x500") # Defines size of 'root'.
root.mainloop()
app = Window(root) # Finally, we use the Window class to make a window under the name 'app'.
CODE#2不使用這樣的概念
from tkinter import *
root=Tk()
topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
button1=Button(topFrame, text="Button 1", fg="red") #fg foreground is optional
button2=Button(topFrame, text="Button 2", fg="blue") #fg is optional
button3=Button(topFrame, text="Button 3", fg="green") #fg is optional
button4=Button(bottomFrame, text="Button 4", fg="black") #fg is optional
button1.pack(side=LEFT,fill=X)
button2.pack(side=LEFT)
button3.pack(side=LEFT)
button4.pack(side=BOTTOM)
root.mainloop()
「更好」是非常主觀的,相對於你正在編寫的程序的複雜性。可能會有關於這兩種方法的爭論。 –
我不認爲它真的很重要,但你的第一個例子不起作用。在調用'mainloop'之後,你不能創建一個窗口,因爲在根窗口被銷燬之前'mainloop'不會返回。 –
@BryanOakley謝謝,我爲自己修復了它。 –