python——GUI tkinter使用

本文记录tkinter学习内容。重复莫烦教程中代码。

来源为莫烦教程:莫烦python_GUI教程

0.窗口主体框架

import tkinter as tk

if __name__ == '__main__':
    window = tk.Tk()
    window.title("my window")
    window.geometry("400x200")
    
    window.mainloop()

 

1.Label & Button 标签和按钮

import tkinter as tk

if __name__ == '__main__':
    window = tk.Tk()
    window.title("my window")
    window.geometry("400x200")
    
    
    #label的相关内容
    l = tk.Label(window,text="this is TKlabel",#设置标签文字
                 bg="green",#设置背景颜色
                 font=('Arial',12),#设置字体和大小
                 width=15,height=12)
    l.pack()#固定窗口位置
    window.mainloop()

也可以通过变量的形式控制label的显示。可以通过button,每点击button,标签变化一次。

import tkinter as tk

def hit_me():
    global on_hit
    if on_hit == False:
        on_hit = True
        var.set("you hit me")
    else:
        on_hit = False
        var.set("")
    
if __name__ == '__main__':
    window = tk.Tk()
    window.title("my window")
    window.geometry("400x200")
    
    #Label
    var = tk.StringVar()
    l = tk.Label(window,textvariable=var,#textvariable可变化
                 bg="green",#设置背景颜色
                 font=('Arial',12),#设置字体和大小
                 width=15,height=5)
    l.pack()#固定窗口位置
    
    #Button
    on_hit=False
    b = tk.Button(window,text="hit me",
                  width=20,height=2,
                  command=hit_me)#command将操作与按钮联系起来
    b.pack()
    window.mainloop()

点击“hit me”button一次显示如下:

再次点击button显示如下:

2.Entry & Text 输入,文本框

import tkinter as tk

def insert_point():
    var = e.get()
    t.insert("insert",var)
    
def insert_end():
    var = e.get()
    t.insert("end",var)
    
if __name__ == '__main__':
    window = tk.Tk()
    window.title("my window")
    window.geometry("400x200")
    
    #创建按钮分别触发两种情况
    b1 = tk.Button(window,text="insert point",
                   width=15,height=2,
                   command=insert_point)
    b1.pack()
    
    b2 = tk.Button(window,text="insert end",
                   command=insert_end)
    b2.pack()
    
    #创建输入框entry,用户的任何输入内容都显示为*
    e = tk.Entry(window,show="*")
    e.pack()
    
    #创建一个文本框用于显示
    t = tk.Text(window,height=2)
    t.pack()
    
   
    window.mainloop()

分别在entry以及text中输入0000,test:

将光标移动到t后,点击button——“insert point“,结果如下:

点击button——”insert end“,结果如下:

3.Listbox列表部件

import tkinter as tk
    
if __name__ == '__main__':
    window = tk.Tk()
    window.title("my window")
    window.geometry("400x200")
    
    #创建一个label用于显示选中的文本
    var1 = tk.StringVar()
    l = tk.Label(window,bg="yellow",textvariable=var1,
                 width=15,height=2)
    l.pack()
    
    #创建一个方法用于按钮的点击事件
    def print_selection():
        value = lb.get(lb.curselection())#获取当前选中的文本
        var1.set(value)#为label设置值
        
    #创建一个按钮
    b1 = tk.Button(window,text="print select",
                   width=15,height=2,
                   command=print_selection)
    b1.pack()
    
    
    #创建listbox和var2,将var2的值赋给listbox
    var2 = tk.StringVar()
    var2.set((11,22,33,44))
    #创建listbox
    lb = tk.Listbox(window,listvariable=var2)
    lb.pack()
    window.mainloop()

在listbox选中22,点击button——”print select“,则22出现在label中。

4.Radiobutton 选择按钮

import tkinter as tk
  
def print_selection():
    l.config(text='you have selected ' + var.get())
    
if __name__ == '__main__':
    window = tk.Tk()
    window.title("my window")
    window.geometry("400x200")
    
    #首选需要定义一个var将radiobutton和label的值联系在一起
    var = tk.StringVar()
    l = tk.Label(window,bg="yellow",
                 width=20,text="empty")
    l.pack()
    
    r1 = tk.Radiobutton(window,text="Option A",
                        variable=var,value="A",
                        command=print_selection)
    r1.pack()
    
    r2 = tk.Radiobutton(window,text="Option B",
                        variable=var,value="B",
                        command=print_selection)
    r2.pack()
    
    window.mainloop()

点击radiobutton——”option B“,结果如下:

5.Scale尺度

import tkinter as tk


def print_selection(v):
    l.config(text="you have selected"+str(v))

if __name__ =="__main__":
    window = tk.Tk()
    window.title("scale")
    
    s = tk.Scale(window,label = "try me",from_=5,to=11,orient=tk.HORIZONTAL,
                 length=200,showvalue=0,tickinterval=2,resolution=0.01,command=print_selection)
    s.pack(side="left")

    l = tk.Label(window,bg="blue",text="empty")
    l.pack(side="right")
    window.mainloop()
  • 参数length这里是指滚动条部件的长度,但注意的是和其他部件width表示不同,width表示的是以字符为单位,比如width=4,就是4个字符的长度,而此处的length=200,是指我们常用的像素为单位,即长度为200个像素

6.Checkbutton勾选项

import tkinter as tk

def print_selection():
    if(var1.get()==1)&(var2.get()==0):
        l.config(text="I love python")
    elif(var1.get()==0)&(var2.get()==1):
        l.config(text="I love C++")
    elif(var1.get()==0)&(var2.get()==0):
        l.config(text="I do not love either")
    else:
        l.config(text="I love both")

if __name__ == "__main__":
    window = tk.Tk()
    window.title("Checkbutton")
    
    var1 = tk.IntVar()
    c1 = tk.Checkbutton(window,text="python",variable=var1,command=print_selection)
    c1.pack()
    
    var2 = tk.IntVar()
    c2 = tk.Checkbutton(window,text="C+=",variable=var2,command=print_selection)
    c2.pack()
    
    l = tk.Label(window)
    l.pack()
    window.mainloop()
   

7.Canvas 画布

import tkinter as tk

def moveit():
    canvas.move(rect,0,2)

if __name__ == "__main__":
    window = tk.Tk()
    window.title("Checkbutton")
    
    canvas = tk.Canvas(window)
    canvas.pack()
    
    img_file = tk.PhotoImage(file="ins.gif")
    image = canvas.create_image(10,10,anchor="nw",image=img_file)
    
    x0,y0,x1,y1 = 50,50,80,80
    line = canvas.create_line(x0,y0,x1,y1)
    oval = canvas.create_oval(x0,y0,x1,y1,fill="red")
    arc = canvas.create_arc(x0+30,y0+30,x1+30,y1+30,start=0,extent=180)
    rect = canvas.create_rectangle(100,30,100+20,30+20)
    
    button = tk.Button(window,text="move rect",command=moveit)
    button.pack()
    
    window.mainloop()

 img_file = tk.PhotoImage(file='ins.gif')这一句是创造一个变量存放ins.gif这张图片。 image = canvas.create_image(10, 10, anchor='nw', image=image_file)里面的参数10,10就是图片放入画布的坐标, 而这里的anchor=nw则是把图片的左上角作为锚定点,在加上刚刚给的坐标位置,即可将图片位置确定。

8.Menubar 菜单


import tkinter as tk

def do_job():
    global counter
    l.config(text = "do"+str(counter))
    counter+=1

if __name__ == "__main__":
    window = tk.Tk()
    window.title("menubar_test")
    #创建一个菜单栏,可以理解为一个容器
    counter = 0
    menubar = tk.Menu(window)
    
    #定义一个空菜单单元
    filemenu = tk.Menu(menubar,tearoff=0)
    
    #将上面定义的空菜单命名为File,放在菜单栏中,就是装入那容器中
    menubar.add_cascade(label="File",menu = filemenu)
    
    #在File中加入“New”的小菜单,即我们平时看到的下拉菜单,每一个小菜单对应命令操作。
    #如果点击这些单元,就会触发do_job的功能
    filemenu.add_command(label="New",command = do_job)
    filemenu.add_command(label="Open",command = do_job)
    filemenu.add_command(label="Save",command = do_job)
    
    filemenu.add_separator()
    
    filemenu.add_command(label="exit",command = window.quit)
    
    submenu = tk.Menu(filemenu)
    filemenu.add_cascade(label="Import",menu=submenu)
    submenu.add_command(label="Submenu1",command=do_job)
    l = tk.Label(window)
    l.pack()
    window.config(menu=menubar)
    window.mainloop()

9.Frame 框架

import tkinter as tk

def change():
    values.set("mode2")

if __name__ == "__main__":
    window = tk.Tk()
    window.title("Frametest")
    
    f1 = tk.Frame(window)
    values = tk.StringVar()
    values.set("mode1")
    l1 = tk.Label(f1,textvariable=values).pack()
    f2 = tk.Frame(window)    
    b = tk.Button(f2,text="hitme",command=change).pack()
    f1.pack()
    f2.pack()
    window.mainloop()

Frame 是一个在 Windows 上分离小区域的部件, 它能将 Windows 分成不同的区,然后存放不同的其他部件. 同时一个 Frame 上也能再分成两个 Frame, Frame 可以认为是一种容器.

10.messagebox部件 

import tkinter as tk

def hit_me():
    tk.messagebox.showinfo(title="Hi",message="hahaha")
#    tk.messagebox.showerror()
#    tk.messagebox.showwarning()
#    tk.messagebox.askquestion()

if __name__ == "__main__":
    window = tk.Tk()
#    window.title("")
     
    b = tk.Button(window,text="hitme",command=hit_me)
    b.pack()
    window.mainloop()

可根据需要选择showerror,showwarning,askquestion.

 

以上记录本人学习过程。如有侵害到您的利益,请与我联系删除。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Abstract Describes the Tkinter widget set for constructing graphical user interfaces (GUIs) in the Python programming language. This publication is available in Web form1 and also as a PDF document2. Please forward any comments to tcc-doc@nmt.edu. Table of Contents 1. What is Tkinter?.......................................................................................................................3 2. A minimal application..............................................................................................................3 3. Definitions..............................................................................................................................4 4. Layout management.................................................................................................................5 4.1. The .grid() method....................................................................................................5 4.2. Other grid management methods...................................................................................6 4.3. Configuring column and row sizes.................................................................................7 4.4. Making the root window resizeable................................................................................8 5. Standard attributes...................................................................................................................8 5.1. Dimensions...................................................................................................................9 5.2. The coordinate system...................................................................................................9 5.3. Colors...........................................................................................................................9 5.4. Type fonts...................................................................................................................10 5.5. Anchors......................................................................................................................11 5.6. Relief styles.................................................................................................................12 5.7. Bitmaps.......................................................................................................................12 5.8. Cursors.......................................................................................................................12 5.9. Images........................................................................................................................14 5.10. Geometry strings........................................................................................................14 5.11. Window names...........................................................................................................15 5.12. Cap and join styles.....................................................................................................15 5.13. Dash patterns.............................................................................................................16 5.14. Matching stipple patterns............................................................................................16 6. The Button widget................................................................................................................17 7. The Canvas widget................................................................................................................19 7.1. Canvas coordinates......................................................................................................20 7.2. The Canvas display list................................................................................................20 7.3. Canvas object IDs........................................................................................................21 7.4. Canvas tags................................................................................................................21 1http://www.nmt.edu/tcc/help/pubs/tkinter/ 2http://www.nmt.edu/tcc/help/pubs/tkinter/tkinter.pdf 1 Tkinter reference New Mexico Tech Computer Center 7.5. CanvastagOrId arguments......................................................................................21 7.6. Methods on Canvas widgets........................................................................................21 7.7. Canvas arc objects.......................................................................................................26 7.8. Canvas bitmap objects.................................................................................................28 7.9. Canvas image objects..................................................................................................29 7.10. Canvas line objects.....................................................................................................29 7.11. Canvas oval objects....................................................................................................31 7.12. Canvas polygon objects..............................................................................................32 7.13. Canvas rectangle objects.............................................................................................34 7.14. Canvas text objects.....................................................................................................35 7.15. Canvas window objects..............................................................................................36 8. The Checkbutton widget......................................................................................................37 9. The Entry widget..................................................................................................................40 9.1. Scrolling an Entry widget............................................................................................43 10. The Frame widget................................................................................................................43 11. The Label widget................................................................................................................44 12. The LabelFrame widget......................................................................................................46 13. The Listbox widget............................................................................................................48 13.1. Scrolling a Listbox widget........................................................................................52 14. The Menu widget..................................................................................................................52 14.1. Menu item creation (coption) options.........................................................................55 14.2. Top-level menus.........................................................................................................56 15. The Menubutton widget......................................................................................................57 16. The Message widget............................................................................................................59 17. The OptionMenu widget.......................................................................................................60 18. The PanedWindow widget....................................................................................................61 18.1. PanedWindow child configuration options...................................................................63 19. The Radiobutton widget....................................................................................................64 20. The Scale widget................................................................................................................67 21. The Scrollbar widget........................................................................................................70 21.1. The Scrollbarcommand callback............................................................................72 21.2. Connecting a Scrollbar to another widget................................................................73 22. The Spinbox widget............................................................................................................73 23. The Text widget..................................................................................................................78 23.1. Text widget indices...................................................................................................80 23.2. Text widget marks....................................................................................................81 23.3. Text widget images...................................................................................................82 23.4. Text widget windows...............................................................................................82 23.5. Text widget tags.......................................................................................................82 23.6. Setting tabs in a Text widget......................................................................................83 23.7. The Text widget undo/redo stack..............................................................................83 23.8. Methods on Text widgets..........................................................................................84 24. Toplevel: Top-level window methods..................................................................................91 25. Universal widget methods.....................................................................................................93 26. Standardizing appearance...................................................................................................101 26.1. How to name a widget class......................................................................................102 26.2. How to name a widget instance.................................................................................102 26.3. Resource specification lines.......................................................................................102 26.4. Rules for resource matching......................................................................................103 27. Connecting your application logic to the widgets...................................................................104 28. Control variables: the values behind the widgets...................................................................104 29. Focus: routing keyboard input.............................................................................................106 New Mexico Tech Computer Center Tkinter reference 2 30. Events................................................................................................................................107 30.1. Levels of binding......................................................................................................108 30.2. Event sequences.......................................................................................................109 30.3. Event types..............................................................................................................109 30.4. Event modifiers........................................................................................................110 30.5. Key names...............................................................................................................111 30.6. Writing your handler: The Event class......................................................................113 30.7. The extra arguments trick..........................................................................................115 30.8. Virtual events...........................................................................................................116 31. Pop-up dialogs....................................................................................................................116 31.1. The tkMessageBox dialogs module..........................................................................116 31.2. The tkFileDialog module.....................................................................................118 31.3. The tkColorChooser module.................................................................................119
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值