zoukankan      html  css  js  c++  java
  • tkinter学习02

     https://docs.python.org/3/library/tkinter.html#tkinter-modules

    http://effbot.org/tkinterbook/

    小例子演示:

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    from tkinter import *   #导入 Tkinter 模块
    
    root =Tk() #实例
    
    label = Label(root, text='Hello world')
    label.pack() # 将小部件放置到主窗口中
    root.mainloop() # 进入消息循环
    

    用类创建

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    from tkinter import *
    
    class App:
        def __init__(self, master):
            frame = Frame(master)
            frame.pack()
    
            self.button = Button(frame, text='Exit Class', fg='blue', command=frame.quit)
    
            self.button.pack()
    
            self.hiButton = Button(frame, text='Say Hi', command=self.say_hi)
            self.hiButton.pack()
    
        def say_hi(self):
            print ("Hi Sundy , Thanks!")
    
    root = Tk()
    app = App(root)
    root.mainloop()
    #root.destroy()
    

     

    #!/usr/bin/env python3
    #-*- coding:utf-8 -*-
    '''
    Administrator 
    2018/10/30 
    '''
    from tkinter import *
    class App:
        def __init__(self,master):
            frame=Frame(master)
            frame.pack()
    
            self.buttom=Button(frame,text="Exit Class",fg="blue",command=frame.quit)
            self.buttom.pack()
    
            self.hiButton=Button(frame,text="Say hi",command=self.say_hi)
            self.hiButton.pack()
    
        def say_hi(self):
            print("Hi,Tom, good job!")
    
    if __name__=="__main__":
        root=Tk()
        app=App(root)
        root.mainloop()
        #root.destroy()
    View Code

    "D:Program Files (x86)python36python.exe" F:/python从入门到放弃/tkinter/10.30/helloclass.py
    Hi,Tom, good job!
    Hi,Tom, good job!
    Hi,Tom, good job!
    

      


    如何设计GUI类库》》》tkinter设计结构 

     

     如果在开发的时候忘记配置样式,可以通过配置文件来配置

    #!/usr/bin/env python3
    #-*- coding:utf-8 -*-
    '''
    Administrator 
    2018/10/30 
    '''
    from tkinter import *
    root=Tk()
    label=Label(root,text="hello world!")
    label.config(cursor="gumby")
    label.config(width=80,height=10,fg='yellow',bg="dark green")
    label.config(font=("times","28","bold"))
    label.pack()
    root.mainloop()

    #!/usr/bin/env python3
    #-*- coding:utf-8 -*-
    '''
    Administrator
    2018/10/30
    '''
    from tkinter import *
    import setting
    root=Tk()
    label=Label(root,text="hello world!")
    setting.config(label)
    # label.config(cursor="gumby")
    # label.config(width=80,height=10,fg='yellow',bg="dark green")
    # label.config(font=("times","28","bold"))
    label.pack()
    root.mainloop()
    helloworld.py
    #!/usr/bin/env python3
    #-*- coding:utf-8 -*-
    '''
    Administrator 
    2018/10/30 
    '''
    def config(obj):
        obj.config(cursor="gumby")
        obj.config(width=80, height=10, fg='yellow', bg="dark green")
        obj.config(font=("times", "28", "bold"))
    setting.py

     Widget Styling  可以配置的组件样式

     http://effbot.org/tkinterbook/tkinter-widget-styling.htm


    样式演示

     1 #!/usr/bin/env python3
     2 #-*- coding:utf-8 -*-
     3 '''
     4 Administrator 
     5 2018/10/30 
     6 '''
     7 from tkinter import *
     8 button = Button(text='SundyButton',padx=10,pady=10)
     9 button.config(cursor='gumby')
    10 button.config(bd=8,relief=FLAT)
    11 button.config(bg='green',fg='yellow')
    12 button.config(font=('Helvetica',10,'bold italic'))
    13 button.pack()
    14 button.mainloop()
    View Code
    relief
    This option controls how to draw the 3D border. It can be set to one of SUNKEN, RAISED, GROOVE, RIDGE, and FLAT.

    事件 和 事件绑定

     http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm

     绑定的三种方式:

    1、通过command = 回调函数  连接事件   (按钮级)

    2、 通过bind 绑定事件   (按钮级)

    3、 通过协议protocol  去监听窗体改变来绑定事件   (系统级)

     

    import tkMessageBox
    
    root= Tk()
    '''
    def button1Click():
        print('button clicked')
    
    button = Button(text='hello', command=button1Click)
    button.pack()
    root.mainloop()
    '''
    def callback(event):
    
        frame.focus_set()
        print('clicked at:', event.x, event.y)
    def key(event):
        print("pressed", repr(event.char))
    
    frame = Frame(root,width=100,height=100)
    frame.bind('<Button-1>',callback)
    frame.bind('<Key>',key)
    frame.pack()
    
    root.protocol('WM_DELETE_WINDOW',)
    root.mainloop()
    View Code
     1 #!/usr/bin/env python3
     2 #-*- coding:utf-8 -*-
     3 '''
     4 Administrator 
     5 2018/10/30 
     6 '''
     7 # import tkMessageBox
     8 from tkinter import *
     9 root= Tk()
    10 
    11 def button1Click():
    12     print('button clicked')
    13 
    14 button = Button(text='hello', command=button1Click)
    15 button.pack()
    16 root.mainloop()
    demo1

    效果:

    command绑定事件的限制性  : 标签没有command属性,没有办法绑定事件

    #!/usr/bin/env python3
    #-*- coding:utf-8 -*-
    '''
    Administrator 
    2018/10/30 
    '''
    # import tkMessageBox
    from tkinter import *
    root= Tk()
    def callback(event):
        print("Button-1 在frame上面 单击鼠标左键,打印出来")
    frame = Frame(root,width=100,height=100)
    frame.bind('<Button-1>',callback)
    frame.pack()
    root.mainloop()
    演示2

     1 #!/usr/bin/env python3
     2 #-*- coding:utf-8 -*-
     3 '''
     4 Administrator 
     5 2018/10/30 
     6 '''
     7 from tkinter import *
     8 import tkinter.messagebox
     9 
    10 root= Tk()
    11 def callback(event):
    12     frame.focus_set()#系统函数,每次点击前得到一个焦点
    13     print('clicked at:', event.x, event.y)#鼠标点击时的x,y轴坐标是多少
    14     print("距离左边的长度:%s  ,距离上面的长度:%s"%(event.x_root,event.y_root))
    15 def key(event):
    16     print("pressed", repr(event.char))#repr 函数  表示将字符用ASCII码打印出来  也可以用str  char输入键盘输入的是什么字符
    17 def closeWindow():
    18     if tkinter.messagebox.askokcancel("提示","是否要退出?"):
    19         root.destroy()
    20 
    21 
    22 
    23 frame = Frame(root,width=100,height=100)
    24 frame.bind('<Button-1>',callback)
    25 frame.config(bg="dark green")
    26 frame.bind('<Key>',key)
    27 frame.pack()
    28 
    29 root.protocol('WM_DELETE_WINDOW',closeWindow)#通过协议监控 WM_DELETE_WINDOW Windows manages 删除 窗口发生时,调用函数  closeWindow
    30 root.mainloop()
    protocol

    在窗体上新建一个窗体 

    #!/usr/bin/env python3
    #-*- coding:utf-8 -*-
    '''
    Administrator 
    2018/10/30
    '''
    from tkinter import *
    
    root = Tk()
    root.title('root window')
    top = Toplevel(bg='red')
    top.title('top level')
    root.mainloop()
    View Code
    #!/usr/bin/env python3
    #-*- coding:utf-8 -*-
    '''
    Administrator
    2018/10/30
    '''
    from tkinter import *
    
    root = Tk()
    root.title('root window')
    # top = Toplevel(bg='red')
    # top.title('top level')
    top = Toplevel()
    top.title("About this application...")
    def about_message():
        return "this is a tkinter demo application"
    msg = Message(top, text=about_message())
    msg.pack()
    
    button = Button(top, text="Dismiss", command=top.destroy)
    button.pack()
    
    root.mainloop()
    View Code

    from tkinter import *
    import tkinter.messagebox
    root = Tk()
    
    def callback():
        if tkinter.messagebox.showerror('Sundy','HI Sundy'):
            print ('Clciked Yes')
        else:
            print ('Clicked No')
    
    button = Button(root, text='Button1', command=callback)
    button.pack()
    root.mainloop()
    消息框

     菜单

    from tkinter import *
    
    def callback():
        print ("called the menu")
    
    root = Tk()
    menu = Menu(root)
    root.config(menu=menu)
    
    filemenu = Menu(menu)
    menu.add_cascade(label='File',menu=filemenu)
    filemenu.add_command(label='New',command=callback)
    filemenu.add_command(label='Open..',command=callback)
    filemenu.add_separator()
    filemenu.add_command(label='Exit',command=callback)
    
    helpmenu = Menu(menu)
    menu.add_cascade(label='Help',menu=helpmenu)
    helpmenu.add_command(label='About..',command=callback)
    
    root.mainloop()
    View Code
    #!/usr/bin/env python3
    #-*- coding:utf-8 -*-
    '''
    Administrator 
    2018/10/30 
    '''
    from tkinter import *
    
    def callback():
        print ("called the menu")
    
    root = Tk()
    menu = Menu(root)
    root.config(menu=menu)#设置一下root 里面菜单 就是上一行实例化的菜单
    
    filemenu = Menu(menu)#添加一个菜单 绑定在menu上面
    menu.add_cascade(label='File',menu=filemenu)#添加一个子菜单,绑定在filemunu上面 并且设置一个名字
    filemenu.add_command(label='New',command=callback)#在菜单上,添加一个命令
    filemenu.add_command(label='Open..',command=callback)
    filemenu.add_separator()#添加一个分割线
    filemenu.add_command(label='Exit',command=callback)
    
    helpmenu = Menu(menu)
    menu.add_cascade(label='Help',menu=helpmenu)
    helpmenu.add_command(label='About..',command=callback)
    
    root.mainloop()
    View Code

    工具条

    #!/usr/bin/env python3
    #-*- coding:utf-8 -*-
    '''
    Administrator 
    2018/10/30 
    '''
    from tkinter import *
    
    root = Tk()
    
    def callback():
        print ("clicked tool bar button ")
    
    toolbar = Frame(root)#由于tkinter没有工具条的类,我们用Frame来代替工具条的布局
    b = Button(toolbar,text='new',width=6,command=callback)
    b.pack(side=LEFT,padx=2,pady=2)
    
    c = Button(toolbar,text='open',width=6,command=callback)
    c.pack(side=LEFT,padx=2,pady=2)
    
    toolbar.pack(side=TOP,fill=X)#放在最上面
    root.mainloop()
    View Code

     

     消息框

    #!/usr/bin/env python3
    #-*- coding:utf-8 -*-
    '''
    Administrator 
    2018/10/30 
    '''
    from tkinter import *
    import tkinter.messagebox
    root = Tk()
    
    def callback():
        if tkinter.messagebox.showerror('Sundy','HI Sundy'):
            print ('Clciked Yes')
        else:
            print ('Clicked No')
    
    button = Button(root, text='Button1', command=callback)
    button.pack()
    root.mainloop()
    View Code

    #!/usr/bin/env python3
    #-*- coding:utf-8 -*-
    '''
    Administrator 
    2018/10/30 
    '''
    from tkinter import *
    import tkinter.messagebox
    root = Tk()
    
    def callback():
        if tkinter.messagebox.askyesno('Sundy','HI Sundy'):
            print ('Clciked Yes')
        else:
            print ('Clicked No')
    
    button = Button(root, text='Button1', command=callback)
    button.pack()
    root.mainloop()
    View Code

     画布

    #!/usr/bin/env python3
    #-*- coding:utf-8 -*-
    '''
    Administrator 
    2018/10/30 
    '''
    from tkinter import *
    
    master = Tk()
    
    w = Canvas(master, width=200, height=100,bg="yellow")
    w.pack()
    
    w.create_line(0, 0, 200, 100)
    w.create_line(0, 100, 200, 0, fill="red", dash=(4, 4))
    
    w.create_rectangle(50, 25, 150, 75, fill="blue")
    
    mainloop()
    View Code

     输入框

    #!/usr/bin/env python3
    #-*- coding:utf-8 -*-
    '''
    Administrator 
    2018/10/30 
    '''
    from tkinter import *
    master=Tk()
    e = Entry(master)
    e.pack()
    
    e.delete(0, END)
    e.insert(0, "a default value")
    print(e.get())
    master.mainloop()
    View Code

     布局

    from Tkinter import *
    
    root = Tk()
    Label(root,text='First').grid(row=0)
    Label(root,text='Second').grid(row=1)
    e1 = Entry(root)
    e2 = Entry(root)
    
    e1.grid(row=0,column=1)
    e2.grid(row=1,column=1)
    
    Button(root,text='OK').grid(row=2)
    
    root.mainloop()
    View Code
    #!/usr/bin/env python3
    #-*- coding:utf-8 -*-
    '''
    Administrator 
    2018/10/30 
    '''
    from tkinter import *
    
    root = Tk()
    Label(root,text='First').grid(row=0)
    Label(root,text='Second').grid(row=1)
    e1 = Entry(root)
    e2 = Entry(root)
    #
    # e1.grid(row=0,column=1)
    # e2.grid(row=1,column=1)
    #
    # Button(root,text='OK').grid(row=2)
    
    root.mainloop()
    View Code

    #!/usr/bin/env python3
    #-*- coding:utf-8 -*-
    '''
    Administrator 
    2018/10/30 
    '''
    from tkinter import *
    
    root = Tk()
    Label(root,text='First').grid(row=0)
    Label(root,text='Second').grid(row=1)
    e1 = Entry(root)
    e2 = Entry(root)
    
    e1.grid(row=0,column=1)
    e2.grid(row=1,column=1)
    
    # Button(root,text='OK').grid(row=2)
    
    root.mainloop()
    View Code

    #!/usr/bin/env python3
    #-*- coding:utf-8 -*-
    '''
    Administrator 
    2018/10/30 
    '''
    from tkinter import *
    
    root = Tk()
    Label(root,text='First').grid(row=0)
    Label(root,text='Second').grid(row=1)
    e1 = Entry(root)
    e2 = Entry(root)
    
    e1.grid(row=0,column=1)
    e2.grid(row=1,column=1)
    
    Button(root,text='OK',width=10).grid(row=2,column=1)
    
    root.mainloop()
    View Code

     状态栏

    from tkinter import *
    
    root = Tk()
    status =Label(root,text='Ln20',bd=1,relief=SUNKEN,anchor=W)
    status.pack(side=BOTTOM, fill=X)
    root.mainloop()
    View Code

    小项目,编写一个记事本
    __author__ = 'Sundy'
    # -*- encoding: utf8 -*-
    
    
    from tkinter import *
    from tkinter.messagebox import *
    from tkinter.filedialog import *
    import os
    
    
    filename = ''
    
    def author():
        showinfo('作者信息','本软件由麦子学院Sundy完成')
    
    
    def about():
    
        showinfo('版权信息.Copyright','本软件版权归属为麦子学院')
    
    def openfile():
        global filename
        filename = askopenfilename(defaultextension = '.txt')
        if filename == '':
            filename = None
        else:
            root.title('FileName:'+os.path.basename(filename))
            textPad.delete(1.0,END)
            f = open(filename,'r')
            textPad.insert(1.0,f.read())
            f.close()
    
    def new():
        global filename
        root.title('未命名文件')
        filename = None
        textPad.delete(1.0,END)
    
    def save():
        global filename
        try:
            f = open(filename,'w')
            msg = textPad.get(1.0,END)
            f.write(msg)
            f.close()
        except:
            saveas()
    
    
    def saveas():
        f = asksaveasfilename(initialfile= '未命名.txt', defaultextension='.txt')
        global filename
        filename = f
        fh = open(f,'w')
        msg = textPad.get(1.0,END)
        fh.write(msg)
        fh.close()
        root.title('FileName:'+os.path.basename(f))
    
    def cut():
        textPad.event_generate('<<Cut>>')
    
    def copy():
        textPad.event_generate('<<Copy>>')
    
    def paste():
        textPad.event_generate('<<Paste>>')
    
    def redo():
        textPad.event_generate('<<Redo>>')
    
    def undo():
        textPad.event_generate('<<Undo>>')
    
    def selectAll():
        textPad.tag_add('sel','1.0',END)
    
    def search():
        topsearch = Toplevel(root)
        topsearch.geometry('300x30+200+250')
        label1 = Label(topsearch,text='Find')
        label1.grid(row=0, column=0,padx=5)
        entry1 = Entry(topsearch,width=20)
        entry1.grid(row=0, column=1,padx=5)
        button1 = Button(topsearch,text='查找')
        button1.grid(row=0, column=2)
    
    
    root = Tk()
    root.title('Sundy Node')
    root.geometry("800x500+100+100")
    
    #Create Menu
    menubar = Menu(root)
    root.config(menu = menubar)
    
    filemenu = Menu(menubar)
    filemenu.add_command(label='新建', accelerator='Ctrl + N', command= new)
    filemenu.add_command(label='打开', accelerator='Ctrl + O',command = openfile)
    filemenu.add_command(label='保存', accelerator='Ctrl + S', command=save)
    filemenu.add_command(label='另存为', accelerator='Ctrl + Shift + S',command=saveas)
    menubar.add_cascade(label='文件',menu=filemenu)
    
    editmenu = Menu(menubar)
    editmenu.add_command(label='撤销', accelerator='Ctrl + Z', command=undo)
    editmenu.add_command(label='重做', accelerator='Ctrl + y', command=redo)
    editmenu.add_separator()
    editmenu.add_command(label = "剪切",accelerator = "Ctrl + X",command=cut)
    editmenu.add_command(label = "复制",accelerator = "Ctrl + C", command=copy)
    editmenu.add_command(label = "粘贴",accelerator = "Ctrl + V", command= paste)
    editmenu.add_separator()
    editmenu.add_command(label = "查找",accelerator = "Ctrl + F", command=search)
    editmenu.add_command(label = "全选",accelerator = "Ctrl + A", command= selectAll)
    menubar.add_cascade(label = "编辑",menu = editmenu)
    aboutmenu = Menu(menubar)
    aboutmenu.add_command(label = "作者", command=author)
    aboutmenu.add_command(label = "版权", command = about)
    menubar.add_cascade(label = "关于",menu=aboutmenu)
    
    #toolbar
    toolbar = Frame(root, height=25,bg='light sea green')
    shortButton = Button(toolbar, text='打开',command = openfile)
    shortButton.pack(side=LEFT, padx=5, pady=5)
    
    shortButton = Button(toolbar, text='保存', command = save)
    shortButton.pack(side=LEFT)
    toolbar.pack(expand=NO,fill=X)
    
    #Status Bar
    status = Label(root, text='Ln20',bd=1, relief=SUNKEN,anchor=W)
    status.pack(side=BOTTOM, fill=X)
    
    #linenumber&text
    lnlabel =Label(root, width=2, bg='antique white')
    lnlabel.pack(side=LEFT, fill=Y)
    
    textPad = Text(root, undo=True)
    textPad.pack(expand=YES, fill=BOTH)
    
    scroll = Scrollbar(textPad)
    textPad.config(yscrollcommand= scroll.set)
    scroll.config(command = textPad.yview)
    scroll.pack(side=RIGHT,fill=Y)
    
    
    
    root.mainloop()
    View Code
  • 相关阅读:
    ASP.NET连接SQL、Access、Excel数据库(二)——连接实例
    浅论cherry机械键盘与其在war3中的表现
    山寨一个PetShop(Task100)——注册界面(配置aspnetdb数据库)
    ASP.NET连接SQL、Access、Excel数据库(三)——工厂模式
    山寨一个PetShop(Task100)——注册界面(配置CreateUserWizard)
    Visual Studio2008的微软官方下载地址
    cocos2d对动画的各种操作
    自定义控件(Task01)——可以设置属性的控件
    Objectivec 枚举类型
    DLL技术应用01 零基础入门学习Delphi44
  • 原文地址:https://www.cnblogs.com/Mengchangxin/p/9874981.html
Copyright © 2011-2022 走看看