Python3 GUI中Tkinter

来源:互联网 发布:淘宝双11报名 编辑:程序博客网 时间:2024/06/06 01:25
GUI中Tkinter详细介绍
Tkinter 是 Python 的标准 GUI 库。Python 使用 Tkinter 可以快速的创建 GUI 应用程序。

由于 Tkinter 是内置到 python 的安装包中、只要安装好 Python 之后就能 import Tkinter 库、而且 IDLE 也是用 Tkinter 编写而成、对于简单的图形界面 Tkinter 还是能应付自如


Tkinter 组件一共有10多种,就不一一介绍了,我就详细介绍一下Tkinter常用组件(四种):
消息(message):消息控件提供了显示多行文本的方法
from tkinter import *                                  #导入Tkinter模块
root=Tk()
me = Message(root,text='one\ntwo\nthree\nfour',   #message:消息,text:文本内容,bg:背景颜色,fg:字体颜色
        bg='blue',fg='ivory')
me.pack(padx=100,pady=200)                                #pack:将Message放置到窗体中,padx:窗体的宽距,pady:窗体的高

me.mainloop()                                            #显示窗体





列表(ListBox):在Listbox窗口小部件是用来显示一个字符串列表给用户
from tkinter import *
root = Tk()
li = ['apple','orange','peach','banana','melon'] #创建一个列表
listb  = Listbox(root)           #  创建两个列表组件
for item in li:                 # 第一个小部件插入数据
    listb.insert(0,item)
listb.pack()                    

root.mainloop()

                

滚动条(Scrollbar):滚动条组件可以添加至任何一个组件,一些组件在界面显示不下时会自动添加滚动条,但是可以使用滚动条组件来对其进行控制 
from tkinter import *
root=Tk()
l=Listbox(root,height=6,width=15)
scroll=Scrollbar(root,command=l.yview)
l.configure(yscrollcommand=scroll.set)
l.pack(side=LEFT)
scroll.pack(side=RIGHT,fill=Y)
for item in range(20):
    l.insert(END,item)
root.mainloop()


画布控件(Canvas):显示图形元素如线条或文本
from tkinter import *
root = Tk()
cv = Canvas(root,bg="white",width=500,heigh=500)
cv.create_polygon(25,0,0,50,50,50,fill="blue") #三角形
cv1=100,100,170,170
cv.create_arc(cv1,start=60,extent=120,fill="green")           #扇形
cv.create_text(150,150,fill="gray",text="adsffasdf")                  #文字
cv.create_oval(300,300,200,200,fill="yellow")                         #圆
cv.create_rectangle(350,350,480,450,fill="red")                      #矩形
cv.pack()

cv.mainloop()



画布控件比较繁琐,内容比较多,出一道画布控件的题给大家做做,巩固巩固吧!
题目:用键盘上下左右键控制三角形上下左右移动,并且点击下键三角形变色


答案:

from tkinter import *
root = Tk()
cv = Canvas(root,bg="white",width=1000,heigh=600)
cv.create_polygon(25,0,0,50,50,50,fill="blue")                    #三角形
cv.pack()
def mymove(event):
    if event.keysym == "Up":
        cv.move(1,0,-30)
    elif event.keysym == "Down":
        cv.move(1,0,30)
        if event.keysym == "Down":
            cv.itemconfigure(1,fill="yellow")
    elif event.keysym == "Left":
        cv.move(1,-30,0)
    else:
        cv.move(1,30,0)
cv.bind_all("<KeyPress-Up>",mymove1)
cv.bind_all("<KeyPress-Down>",mymove1)
cv.bind_all("<KeyPress-Left>",mymove1)
cv.bind_all("<KeyPress->",mymove1)

cv.mainloop()




阅读全文
0 0
原创粉丝点击