GUI的终极选择:Tkinter
一、初试GUI
import tkinter as tk
#实例化一个TK,用于容纳整个GUI程序
app = tk.Tk()
#设置标题栏
app.title("Demo")
#Label组件是最常用的组件之一
#Label组件用于显示文本、图标、图片、文本
theLabel = tk.Label(app,text="我的第一个窗口程序")
#pack方法用于自动调节自身的尺寸和位置
theLabel.pack()
#窗口的主事件循环
#这基本是GUI程序的最后一行代码
app.mainloop()
二、将GUI封装成类
import tkinter as tk
class APP:
def __init__(self,master):
#框架是在复杂的组件中起到分组的作用
frame = tk.Frame(master)
frame.pack()
#创建一个按钮组件
self.hi_there = tk.Button(frame,text="打招呼",fg="blue")
self.hi_there.pack()
root = tk.Tk()
app = APP(root)
root.mainloop()
但是,按下按钮并没有反应,所以我们需要给他设置响应。
class APP:
def __init__(self,master):
frame = tk.Frame(master)
frame.pack()
self.hi_there = tk.Button(frame,text="打招 呼",fg="blue",command=self.say_hi) #新增command
self.hi_there.pack()
def say_hi(self):
print("用户你好!")
但是问题又出现了,细心的读者也许会发现,按钮一直在最上面,pack默认设置是在top(一共四个位置:top/bottom/left/right)
frame.pack(side=tk.LEFT,padx=10,pady=10)
三、加图片
from tkinter import *
root = Tk()
textLabel(root,text="您好用户!")
textLabel.pack(side=LEFT)
#用Label显示图像
photo = PhotoImage(file="timg[1].jpg")
imgLabel = Label(root,image=photo)
imgLabel.pack(side=RIGHT)
mainloop()