Python 新手村
用 Python 打造你的遊戲
2020
小草、RexWu
Part 7
ctl12345
GUI
終於看得到惹
Python's easiest GUI
Tkinter
import tkinter as tk
window = tk.Tk()
msg = tk.Label(master=window, text="你好!")
msg.pack()
window.mainloop()
簡單的視窗
import tkinter as tk
window = tk.Tk()
window.geometry("500x500")
msg = tk.Label(master=window, text="你好!")
msg.pack()
window.mainloop()
簡單的視窗(指定大小)
import tkinter as tk
window = tk.Tk()
window.geometry("500x500")
msg = tk.Label(master=window, text="你好!")
msg.pack()
window.mainloop()
文字標籤
import tkinter as tk
window = tk.Tk()
def clk():
print("尼亂按 ><")
btn = tk.Button(master=window, text="按我!", command=clk)
msg.pack()
window.mainloop()
按鈕
import tkinter as tk
window = tk.Tk()
def clk():
btn["text"] = "不要亂按 ><"
btn = tk.Button(master=window, text="按我!", command=clk)
btn.pack()
window.mainloop()
變更元件文字
frame - side
import tkinter as tk
window = tk.Tk()
window.geometry("300x300")
label0 = tk.Label(text="我在最上面!")
label0.pack(side = tk.TOP)
label3 = tk.Label(text="我在左邊 ( ~'ω')~ ")
label3.pack(side = tk.LEFT)
label4 = tk.Label(text=" ~('ω'~ ) 窩在右邊")
label4.pack(side = tk.RIGHT)
window.mainloop()
frame - grid
import tkinter as tk
window = tk.Tk()
window.geometry("500x500")
frame = tk.Frame()
frame.grid(row=0, column=0)
label = tk.Label(master=frame, text="左上角")
label.pack()
frame = tk.Frame()
frame.grid(row=1, column=1)
label = tk.Label(master=frame, text="右下角")
label.pack()
window.mainloop()
frame - grid 結合迴圈
import tkinter as tk
window = tk.Tk()
window.geometry("500x500")
def clk():
print("不要亂按><")
for i in range(3):
for j in range(3):
frame = tk.Frame()
frame.grid(row=i, column=j)
btn = tk.Button(master=frame, text=str(i) + str(j), width=5, command=clk)
btn.pack()
window.mainloop()
文字有點小 要怎麼辦呢?
from tkinter import *
from tkinter.font import Font
window = Tk()
textLabel = Label(window,
font = Font(size = 80),
text = '我是變大的字串')
textLabel.pack()
mainloop()
使用 tkinter.font
文字有點單調 加點顏色吧
from tkinter import *
from tkinter.font import Font
window = Tk()
textLabel = Label(window,
font = Font(size = 80),
bg = 'blue',
fg = 'red',
text = '我是變大的字串')
textLabel.pack()
mainloop()
GUI 版面配置
Label.pack() #自動配置
Label.place(x = 100, y = 150) #精確一些的配置
Label.grid(column = 0, row = 0) #好用又不麻煩
GUI 的變數
StringVar() #字串
IntVar() #整數
DoubleVar() #浮點數
BooleanVar() #布林值
變數的值
num = IntVar() #建立變數
num.set(10) #設定變數的值
i = num.get() #取得變數的值
print(i)
num.set(100)
print(num.get())
透過 GUI 和程式對話
from tkinter import *
window = Tk()
inputNum = Entry(window)
def iuput():
newNum = inputNum.get()
print(newNum)
inputBtn = Button(window, text = "輸入", command = iuput)
inputNum.pack()
inputBtn.pack()
mainloop()
實作一下
還記得終極密碼嗎?
來加上 GUI 吧
Python 新手村 2020 Part 7
By Rex Wu
Python 新手村 2020 Part 7
- 67