【python】tkinter教程、35个tkinter⽰例代码和GUI图⽰
#⽰例1:主窗⼝及标题
import tkinter as tk
app = tk.Tk() #根窗⼝的实例(root窗⼝)
app.title('Tkinter root window') #根窗⼝标题
theLabel = tk.Label(app, text='我的第1个窗⼝程序!') #label组件及⽂字内容
theLabel.pack() #pack()⽤于⾃动调节组件的尺⼨
app.mainloop() #窗⼝的主事件循环,必须的。
#⽰例2:按钮
import tkinter as tk
class APP:
def __init__(self, master): #root 传参赋值给master
frame = tk.Frame(master) #frame 组件
frame.pack(side=tk.LEFT, padx=10, pady=10)
self.hi_there = tk.Button(frame, text='打招呼', bg='black', fg='white', command=self.say_hi) #Button按钮, command中调⽤定义的⽅法
self.hi_there.pack()
def say_hi(self):
print('卧槽,居然打了个招呼!~')
root = tk.Tk()
app = APP(root)
root.mainloop()
#⽰例3:图⽚
from tkinter import *
root = Tk()
textLabel = Label(root,
text='请重试!\n您的操作不被允许!', #⽂字⽀持换⾏ justify=LEFT, #左对齐
padx=10, #左边距10px
pady=10) #右边距10px
textLabel.pack(side=LEFT)
#显⽰图⽚
photo = PhotoImage(file='tk_image.png')
imageLabel = Label(root, image=photo)
imageLabel.pack(side=RIGHT)
mainloop()
#⽰例4:背景
from tkinter import *
root = Tk()
photo = PhotoImage(file='tk4_bg.png')
theLabel = Label(root,
text='⽣存还是毁灭\n这是⼀个问题', justify=LEFT,
image=photo,
compound=CENTER,
font=('华⽂⾪书', 20),
fg='blue')
theLabel.pack()
mainloop()
#⽰例5:按钮交互
from tkinter import *
def callback():
var.set('吹吧你,我才不信呢!')
root = Tk()
frame1 = Frame(root)
frame2 = Frame(root)
var = StringVar()
var.set('请重试!\n您的操作不被允许!') textLabel = Label(frame1,
textvariable=var,
justify=LEFT) #左对齐
textLabel.pack(side=LEFT)
#显⽰图⽚
photo = PhotoImage(file='tk_image.png')
imageLabel = Label(root, image=photo)
imageLabel.pack(side=RIGHT)
theButton = Button(frame2, text='我是超级管理员', command=callback) theButton.pack()
frame1.pack(padx=10, pady=10)
frame2.pack(padx=10, pady=10)
mainloop()
#⽰例6:选项按钮
from tkinter import *
root = Tk()
v = IntVar()
c = Checkbutton(root, text='测试⼀下', variable=v) #v⽤来存放选中状态c.pack()
l = Label(root, textvariable=v)
l.pack() #未选中显⽰为0,选中显⽰1
mainloop()
#⽰例7:多个⽅框选项
from tkinter import *
python新手代码示例root = Tk()
GIRLS = ['西施', '貂蝉', '王昭君', '杨⽟环']
v = []
for girl in GIRLS:
v.append(IntVar())
b = Checkbutton(root, text=girl, variable=v[-1])
b.pack(anchor=W) #设置对齐⽅位,东E南S西W北N
mainloop()
#⽰例8:多个圆点选项 Radiobutton
from tkinter import *
root = Tk()
v = IntVar()
Radiobutton(root, text='one', variable=v, value=1).pack(anchor=W) Radiobutton(root, text='two', variable=v, value=2).pack(anchor=W) Radiobutton(root, text='three', variable=v, value=3).pack(anchor=W) Radiobutton(root, text='four', variable=v, value=4).pack(anchor=W)
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论