日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

第十二章 图形用户界面

發布時間:2023/12/1 编程问答 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 第十二章 图形用户界面 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

第十二章 圖形用戶界面

GUI就是包含按鈕、文本框等控件的窗口
Tkinter是事實上的Python標準GUI工具包

創建GUI示例應用程序

初探

導入tkinter

import tkinter as tk

也可導入這個模塊的所有內容

from tkinter import *

要創建GUI,可創建一個將充當主窗口的頂級組件(控件)。
為此,可實例化一個Tk對象。

top = Tk()

調用函數mainloop以進入Tkinter主事件循環,而不是直接退出程序。

from tkinter import * top = Tk() mainloop()

效果圖如下:

創建按鈕,可實例化Button類。
需要使用布局管理器(也叫幾何體管理器)來顯示按鈕的位置(使用管理器pack)
按鈕也可以指定一些文本、給按鈕添加行為

from tkinter import * button = Button() button.pack() button['text'] = 'Click me!' def clicked():print("I was clicked!")mainloop()

效果圖如下:

可以不分別給屬性賦值,而使用方法config同時設置多個屬性。
button.config(text='Click me!',command=clicked)
還可使用控件的構造函數來配置控件。
Button(text='click me too!',command=clicked).pack()

布局

對控件調用方法pack時,將把控件放在其父控件(主控件)中。

from tkinter import * Label(text="I'm in the first window!").pack() second = Toplevel() Label(second,text="I'm in the second window!").pack()

效果圖如下:
Toplevel類表示除主窗口外的另一個頂級窗口,而Label就是文本標簽。

一列按鈕

from tkinter import * for i in range(10):Button(text=i).pack()mainloop()

效果圖如下:
要快速了解可用的選項,可執行如下命令

help(Pack.config) ''' Help on function pack_configure in module tkinter:pack_configure(self, cnf={}, **kw)Pack a widget in the parent widget. Use as options:after=widget - pack it after you have packed widgetanchor=NSEW (or subset) - position widget according togiven directionbefore=widget - pack it before you will pack widgetexpand=bool - expand widget if parent size growsfill=NONE or X or Y or BOTH - fill widget if widget growsin=master - use master to contain this widgetin_=master - see 'in' option descriptionipadx=amount - add internal padding in x directionipady=amount - add internal padding in y directionpadx=amount - add padding in x directionpady=amount - add padding in y directionside=TOP or BOTTOM or LEFT or RIGHT - where to add this widget. '''

還有其他的布局管理器,具體地說是gridplace

help(Grid.configure) ''' Help on function grid_configure in module tkinter:grid_configure(self, cnf={}, **kw)Position a widget in the parent widget in a grid. Use as options:column=number - use cell identified with given column (starting with 0)columnspan=number - this widget will span several columnsin=master - use master to contain this widgetin_=master - see 'in' option descriptionipadx=amount - add internal padding in x directionipady=amount - add internal padding in y directionpadx=amount - add padding in x directionpady=amount - add padding in y directionrow=number - use cell identified with given row (starting with 0)rowspan=number - this widget will span several rowssticky=NSEW - if cell is larger on which sides will thiswidget stick to the cell boundary ''' help(Place.config) ''' Help on function place_configure in module tkinter:place_configure(self, cnf={}, **kw)Place a widget in the parent widget. Use as options:in=master - master relative to which the widget is placedin_=master - see 'in' option descriptionx=amount - locate anchor of this widget at position x of mastery=amount - locate anchor of this widget at position y of masterrelx=amount - locate anchor of this widget between 0.0 and 1.0relative to width of master (1.0 is right edge)rely=amount - locate anchor of this widget between 0.0 and 1.0relative to height of master (1.0 is bottom edge)anchor=NSEW (or subset) - position anchor according to given directionwidth=amount - width of this widget in pixelheight=amount - height of this widget in pixelrelwidth=amount - width of this widget between 0.0 and 1.0relative to width of master (1.0 is the same widthas the master)relheight=amount - height of this widget between 0.0 and 1.0relative to height of master (1.0 is the sameheight as the master)bordermode="inside" or "outside" - whether to take border width ofmaster widget into account '''

事件處理

通過設置屬性command給按鈕指定動作(action),這是一種特殊的事件處理。
Tkinter還提供了更通用的事件處理機制:方法bind。要讓控件對特定的事件進行處理,可對其調用方法bind,并指定事件的名稱和要使用的函數。

點哪兒顯示所點擊的坐標位置(鼠標單擊事件,提供x和y坐標)
其中是使用鼠標左按鈕(按鈕1)單擊的事件名稱。
將這種事件關聯到函數callback。
這樣,每當用戶在窗口top中單擊時,都將調用這個函數。向函數callback傳遞一個event對象,這個對象包含的屬性隨事件類型而異。

from tkinter import * top = Tk() def callback(event):print(event.x,event.y)top.bind('<Button-1>',callback)#結果為:'2435082162376callback' mainloop()

效果圖如下:
當然也可以查詢幫助

help(Tk.bind) ''' Help on function bind in module tkinter:bind(self, sequence=None, func=None, add=None)Bind to this widget at event SEQUENCE a call to function FUNC.SEQUENCE is a string of concatenated eventpatterns. An event pattern is of the form<MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is oneof Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,B3, Alt, Button4, B4, Double, Button5, B5 Triple,Mod1, M1. TYPE is one of Activate, Enter, Map,ButtonPress, Button, Expose, Motion, ButtonReleaseFocusIn, MouseWheel, Circulate, FocusOut, Property,Colormap, Gravity Reparent, Configure, KeyPress, Key,Unmap, Deactivate, KeyRelease Visibility, Destroy,Leave and DETAIL is the button number for ButtonPress,ButtonRelease and DETAIL is the Keysym for KeyPress andKeyRelease. Examples are<Control-Button-1> for pressing Control and mouse button 1 or<Alt-A> for pressing A and the Alt key (KeyPress can be omitted).An event pattern can also be a virtual event of the form<<AString>> where AString can be arbitrary. Thisevent can be generated by event_generate.If events are concatenated they must appear shortlyafter each other.FUNC will be called if the event sequence occurs with aninstance of Event as argument. If the return value of FUNC is"break" no further bound function is invoked.An additional boolean parameter ADD specifies whether FUNC willbe called additionally to the other bound function or whetherit will replace the previous function.Bind will return an identifier to allow deletion of the bound function withunbind without memory leak.If FUNC or SEQUENCE is omitted the bound function or listof bound events are returned. '''

最終的程序

簡單的GUI文本編輯器
1,需要輸入所要編輯的文本地址
2,點擊Open,即可打開該文本文件
3,在下方編輯欄中可隨意編輯
4,點擊Save即可保存

from tkinter import * from tkinter.scrolledtext import ScrolledText def load():with open(filename.get()) as file:contents.delete('1.0', END)contents.insert(INSERT, file.read())def save():with open(filename.get(), 'w') as file:file.write(contents.get('1.0', END))top = Tk() top.title("Simple Editor")contents = ScrolledText() contents.pack(side=BOTTOM, expand=True, fill=BOTH)filename = Entry() filename.pack(side=LEFT, expand=True, fill=X)Button(text='Open', command=load).pack(side=LEFT) Button(text='Save', command=save).pack(side=LEFT)mainloop()

效果圖如下:

小結

概念描述
圖形用戶界面(GUI)GUI有助于讓應用程序對用戶更友好。并非所有的程序都需要GUI,但只要程序需要與用戶交互,GUI就可能很有幫助。
TkinterTkinter是一個跨平臺的Python GUI工具包,成熟而且使用廣泛。
布局通過指定組件的幾何屬性,很容易對其進行定位,但要確保它們在父窗口的大小發生變化時做出正確的反應,就必須使用布局管理器。
事件處理GUI工具包中用戶觸發事件執行的操作。要發揮作用,程序可能需要響應某些事件,否則用戶將無法與之交互。在Tkinter中,要給組件添加事件處理程序,可使用方法bind。

總結

以上是生活随笔為你收集整理的第十二章 图形用户界面的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。