私は、Tkinterを使って基本的なウィンドウを作るという2つのチュートリアルを見てきました。チュートリアルの1つは、関数を持つクラスを使用してウィンドウを初期化し、組み立てます。他のチュートリアルでは、クラスや関数を使わずにウィンドウを作成しました。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ありがとう、私はそれを自分で修正しました。 –