Tkinter 組件html
標準屬性python
幾何管理程序員
代碼實例:算法
二、 Entry & Textcanvas
三、Listbox列表app
五、Scale尺度ide
Python 提供了多個圖形開發界面的庫,幾個經常使用 Python GUI 庫以下:
Tkinter: Tkinter 模塊(Tk 接口)是 Python 的標準 Tk GUI 工具包的接口 .Tk 和 Tkinter 能夠在大多數的 Unix 平臺下使用,一樣能夠應用在 Windows 和 Macintosh 系統裏。Tk8.0 的後續版本能夠實現本地窗口風格,並良好地運行在絕大多數平臺中。
wxPython:wxPython 是一款開源軟件,是 Python 語言的一套優秀的 GUI 圖形庫,容許 Python 程序員很方便的建立完整的、功能鍵全的 GUI 用戶界面。
Jython:Jython 程序能夠和 Java 無縫集成。除了一些標準模塊,Jython 使用 Java 的模塊。Jython 幾乎擁有標準的Python 中不依賴於 C 語言的所有模塊。好比,Jython 的用戶界面將使用 Swing,AWT或者 SWT。Jython 能夠被動態或靜態地編譯成 Java 字節碼。
Tkinter 是 Python 的標準 GUI 庫。Python 使用 Tkinter 能夠快速的建立 GUI 應用程序。
因爲 Tkinter 是內置到 python 的安裝包中、只要安裝好 Python 以後就能 import Tkinter 庫、並且 IDLE 也是用 Tkinter 編寫而成、對於簡單的圖形界面 Tkinter 仍是能應付自如。
注意:Python3.x 版本使用的庫名爲 tkinter,即首寫字母 T 爲小寫。
import tkinter
#建立一個GUI程序 #一、導入 Tkinter 模塊 #二、建立控件 #三、指定這個控件的 master, 即這個控件屬於哪個 #四、告訴 GM(geometry manager) 有一個控件產生了。
主窗口經常使用操做:
1 root.title('標題名')#修改框體的名字,也可在建立時使用className參數來命名; 2 root.resizable(0,0) # 框體大小可調性,分別表示x,y方向的可變性; 3 root.geometry('250x150')#指定主框體大小; 4 root.quit() # 退出; 5 root.update_idletasks() 6 root.update()#刷新頁面;
Tkinter的提供各類控件,如按鈕,標籤和文本框,一個GUI應用程序中使用。這些控件一般被稱爲控件或者部件。
目前有15種Tkinter的部件。咱們提出這些部件以及一個簡短的介紹,在下面的表:
(在Tkinter中窗口部件類沒有分級;全部的窗口部件類在樹中都是兄弟。)
標準屬性也就是全部控件的共同屬性,如大小,字體和顏色等等
Tkinter控件有特定的幾何狀態管理方法,管理整個控件區域組織,一下是Tkinter公開的幾何管理類:包、網格、位置
組件的放置和排版(pack,grid,place) 屬性參數
pack組件設置位置屬性參數: after: 將組件置於其餘組件以後; before: 將組件置於其餘組件以前; anchor: 組件的對齊方式,頂對齊'n',底對齊's',左'w',右'e' side: 組件在主窗口的位置,能夠爲'top','bottom','left','right'(使用時tkinter.TOP,tkinter.E); fill 填充方式 (Y,垂直,X,水平) expand 1可擴展,0不可擴展 grid組件使用行列的方法放置組件的位置,參數有: column: 組件所在的列起始位置; columnspam: 組件的列寬; row: 組件所在的行起始位置; rowspam: 組件的行寬; place組件能夠直接使用座標來放置組件,參數有: anchor: 組件對齊方式; NW N NE E SE S SW W CENTER x: 組件左上角的x座標; y: 組件右上角的y座標; relx: 組件相對於窗口的x座標,應爲0-1之間的小數; rely: 組件相對於窗口的y座標,應爲0-1之間的小數; width: 組件的寬度; heitht: 組件的高度; relwidth: 組件相對於窗口的寬度,0-1; relheight: 組件相對於窗口的高度,0-1;
# -*- coding: utf-8 -*- # @Time : 2018/3/31 0:15 # @Author : TanRong # @Software: PyCharm # @File : lable_button.py from tkinter import * root = Tk() #根窗口 root.title('Lable & Button') #主窗口標題 root.geometry('800x600') #主窗口大小,中間的爲英文字母x var = StringVar() #tk裏面特定的字符串形式 lable = Label(root, textvariable=var, bg='green', font=('Arial', 12), width=15, height=2) lable.pack() # lable.place() 安放到具體位置 on_hit = False def hit_me(): global on_hit #必須標出它是global的 if on_hit == False: on_hit = True var.set('線性迴歸') else: on_hit = False var.set('') button = Button(root, text='執行', width=15, height=2, command=hit_me) button.pack() root.mainloop()
anchor: 指定按鈕上文本的位置; background(bg) 指定按鈕的背景色; bitmap: 指定按鈕上顯示的位圖; borderwidth(bd) 指定按鈕邊框的寬度; command: 指定按鈕消息的回調函數; cursor: 指定鼠標移動到按鈕上的指針樣式; font: 指定按鈕上文本的字體; foreground(fg) 指定按鈕的前景色; height: 指定按鈕的高度; image: 指定按鈕上顯示的圖片; state: 指定按鈕的狀態(disabled); text: 指定按鈕上顯示的文本; width: 指定按鈕的寬度 padx 設置文本與按鈕邊框x的距離,還有pady; activeforeground 按下時前景色 textvariable 可變文本,與StringVar等配合着用
Anchor 標籤中文本的位置; background(bg) 背景色; foreground(fg) 前景色; borderwidth(bd) 邊框寬度; width 標籤寬度; height 標籤高度; bitmap 標籤中的位圖; font 字體; image 標籤中的圖片; justify 多行文本的對齊方式; text 標籤中的文本,可使用'\n'表示換行 textvariable 顯示文本自動更新,與StringVar等配合着用
# -*- coding: utf-8 -*- # @Time : 2018/4/1 0:30 # @Author : TanRong # @Software: PyCharm # @File : entry_text.py from tkinter import * root = Tk(); root.title('Entry & Text') root.geometry('800x600') entry = Entry(root, show='*') entry.pack() def insert_point(): var = entry.get() text.insert('insert', var) def insert_end(): var = entry.get() # text.insert('end', var) 插入到末尾 text.insert('2.2', var) #插入到第二行第三位 b1 = Button(root, text='insert point', width=15, height=2, command=insert_point) b1.pack() b2 = Button(root, text='insert end', command=insert_end) b2.pack() text = Text(root, height=2) text.pack() root.mainloop()
background(bg) 文本框背景色; foreground(fg) 前景色; selectbackground 選定文本背景色; selectforeground 選定文本前景色; borderwidth(bd) 文本框邊框寬度; font 字體; show 文本框顯示的字符,若爲*,表示文本框爲密碼框; state 狀態; width 文本框寬度 textvariable 可變文本,與StringVar等配合着用
1 # -*- coding: utf-8 -*- 2 # @Time : 2018/4/1 0:45 3 # @Author : TanRong 4 # @Software: PyCharm 5 # @File : listbox.py 6 7 from tkinter import * 8 9 root = Tk(); 10 root.title('Listbox') 11 root.geometry('400x300') 12 13 var1 = StringVar() 14 lable = Label(root, bg='yellow', width=4, textvariable=var1) 15 lable.pack() 16 17 def print_selection(): 18 value = lb.get(lb.curselection()) #獲得光標選定的列表項 19 var1.set(value) 20 21 button = Button(root, text='print selection', width=15, height=2, command=print_selection) 22 button.pack() 23 24 var2 = StringVar() 25 var2.set((11,22,33,55)) 26 lb = Listbox(root, listvariable=var2) 27 list_items = [1,2,3,4] 28 for item in list_items: 29 lb.insert('end', item) 30 lb.insert(1, 'first') #索引插入,第2位插入first 31 lb.insert(2, 'second') 32 lb.delete(2)#索引刪除 33 lb.pack() 34 35 root.mainloop()
1 # -*- coding: utf-8 -*- 2 # @Time : 2018/4/1 0:59 3 # @Author : TanRong 4 # @Software: PyCharm 5 # @File : radiobutton.py 6 7 import tkinter as tk 8 9 root = tk.Tk() 10 root.title("Radiobutton") 11 root.geometry('400x300') 12 13 var = tk.StringVar() 14 lable = tk.Label(root, text='empty', bg='yellow', width=25 ) 15 lable.pack() 16 17 def print_selection(): 18 lable.config(text='you have selected ' + var.get()) #lable從新設置text 19 r1 = tk.Radiobutton(root, text='OptionA', 20 variable=var, value='A', 21 command=print_selection) 22 r1.pack() 23 r2 = tk.Radiobutton(root, text='OptionB', 24 variable=var, value='B', 25 command=print_selection) 26 r2.pack() 27 r3 = tk.Radiobutton(root, text='OptionC', 28 variable=var, value='C', 29 command=print_selection) 30 r3.pack() 31 32 root.mainloop()
anchor 文本位置; background(bg) 背景色; foreground(fg) 前景色; borderwidth 邊框寬度; width 組件的寬度; height 組件高度; bitmap 組件中的位圖; image 組件中的圖片; font 字體; justify 組件中多行文本的對齊方式; text 指定組件的文本; value 指定組件被選中中關聯變量的值; variable 指定組件所關聯的變量; indicatoron 特殊控制參數,當爲0時,組件會被繪製成按鈕形式; textvariable 可變文本顯示,與StringVar等配合着用
1 # -*- coding: utf-8 -*- 2 # @Time : 2018/4/1 1:17 3 # @Author : TanRong 4 # @Software: PyCharm 5 # @File : scale.py 6 import tkinter as tk 7 8 root = tk.Tk() 9 root.title("Scale") 10 root.geometry('400x300') 11 12 lable = tk.Label(root, text='empty', bg='yellow', width=25 ) 13 lable.pack() 14 15 def print_selection(v): 16 lable.config(text='you have selected '+ v) 17 #5-11是取值範圍;HORIZONTAL指水平;length是長度200像素;showvalue爲1是將value顯示在scale上面; 18 # tickinterval是標籤的單位長度,好比隔3個數值顯示一個單位;resolution=0.01保留2位小數 19 # Scale中的執行函數是有默認傳入值的,就是標籤的值 20 scale = tk.Scale(root, label='try me', from_=5, to=11, 21 orient=tk.HORIZONTAL, length=200, 22 showvalue=1, tickinterval=3, resolution=0.01, 23 command=print_selection) 24 scale.pack() 25 root.mainloop()
1 # -*- coding: utf-8 -*- 2 # @Time : 2018/4/1 15:19 3 # @Author : TanRong 4 # @Software: PyCharm 5 # @File : checkbutton.py 6 7 import tkinter as tk 8 9 root = tk.Tk() 10 root.title('Checkbutton') 11 root.geometry('400x300') 12 13 label = tk.Label(root, bg='yellow', width=20, text='Empty') 14 label.pack() 15 16 17 def print_selectioin(): 18 var = tk.StringVar() 19 if var1.get() + var2.get() == 2: 20 var = 'I love both' 21 elif var1.get() + var2.get() == 0: 22 var = 'I do not love either' 23 else: 24 if var1.get() == 1: 25 var = 'I love Python' 26 else: 27 var = 'I love C++' 28 29 label.config(text=var) 30 31 var1 = tk.IntVar() 32 var2 = tk.IntVar() 33 c1 = tk.Checkbutton(root, text='Python', variable=var1, onvalue=1, offvalue=0, 34 command=print_selectioin) 35 c2 = tk.Checkbutton(root, text='C++', variable=var2, onvalue=1, offvalue=0, 36 command=print_selectioin) 37 c1.pack() 38 c2.pack() 39 root.mainloop()
anchor 文本位置; background(bg) 背景色; foreground(fg) 前景色; borderwidth 邊框寬度; width 組件的寬度; height 組件高度; bitmap 組件中的位圖; image 組件中的圖片; font 字體; justify 組件中多行文本的對齊方式; text 指定組件的文本; value 指定組件被選中中關聯變量的值; variable 指定組件所關聯的變量; indicatoron 特殊控制參數,當爲0時,組件會被繪製成按鈕形式; textvariable 可變文本顯示,與StringVar等配合着用
1 # -*- coding: utf-8 -*- 2 # @Time : 2018/4/1 16:02 3 # @Author : TanRong 4 # @Software: PyCharm 5 # @File : canvas.py 6 7 import tkinter as tk 8 9 root = tk.Tk() 10 root.title('Canvas') 11 root.geometry('400x300') 12 13 14 canvas = tk.Canvas(root, bg='blue', height=100, width=200) 15 image_file = tk.PhotoImage(file='../images/23.gif') 16 image = canvas.create_image(10, 10, anchor='nw', image=image_file) #是圖片錨定的點 17 18 x0,y0,x1,y1 = 50,50,80,80 19 line = canvas.create_line(x0,y0,x1,y1) 20 21 oval = canvas.create_oval(x0,y0,x1,y1,fill='red') #x0,y0,x1,y1是圓的外接正方形 22 arc = canvas.create_arc(x0+30,y0+30,x1+30,y1+30, start=0, extent=160)#0-160角度範圍 23 rect = canvas.create_rectangle(100,30,100+20,30+20) 24 canvas.pack() 25 26 def moveit(): 27 canvas.move(rect, 1, 2) #rect是正方形id,1是x方向移動,2是y方向移動 28 button = tk.Button(root, text='move', command=moveit).pack() 29 30 root.mainloop()
background(bg) 背景色; foreground(fg) 前景色; borderwidth 組件邊框寬度; width 組件寬度; height 高度; bitmap 位圖; image 圖片; 繪圖的方法主要如下幾種: create_arc 圓弧; create_bitmap 繪製位圖,支持XBM; create_image 繪製圖片,支持GIF(x,y,image,anchor); create_line 繪製支線; create_oval; 繪製橢圓; create_polygon 繪製多邊形(座標依次羅列,不用加括號,還有參數,fill,outline); create_rectangle 繪製矩形((a,b,c,d),值爲左上角和右下角的座標); create_text 繪製文字(字體參數font,); create_window 繪製窗口; delete 刪除繪製的圖形; itemconfig 修改圖形屬性,第一個參數爲圖形的ID,後邊爲想修改的參數; move 移動圖像(1,4,0),1爲圖像對象,4爲橫移4像素,0爲縱移像素,而後用root.update()刷新便可看到圖像的移動,爲了使屢次移動變得可視,最好加上time.sleep()函數; 只要用create_方法畫了一個圖形,就會自動返回一個ID,建立一個圖形時將它賦值給一個變量,須要ID時就可使用這個變量名。 coords(ID) 返回對象的位置的兩個座標(4個數字元組); 對於按鈕組件、菜單組件等能夠在建立組件時經過command參數指定其事件處理函數。方法爲bind;或者用bind_class方法進行類綁定,bind_all方法將全部組件事件綁定到事件響應函數上。
1 # -*- coding: utf-8 -*- 2 # @Time : 2018/4/1 16:02 3 # @Author : TanRong 4 # @Software: PyCharm 5 # @File : menubar.py 6 import tkinter as tk 7 8 root = tk.Tk() 9 root.title("Menubar") 10 root.geometry('400x300') 11 12 label = tk.Label(root, text='', bg='yellow') 13 label.pack() 14 15 counter = 0 16 def do_job(): 17 global counter 18 label.config(text='do '+ str(counter)) #若是直接將pack()寫在label定義的後面,則在這裏就會出現label沒有config屬性的錯誤 19 counter += 1 20 menubar = tk.Menu(root) 21 filemenu = tk.Menu(menubar, tearoff=0)#tearoff是指不可分割 它的值只有0和1,將tearoff設置爲1之後,就是代表這個菜單是能夠獨立出來的,若是是0的話就不能夠獨立出來。代碼演示一下便可。 22 menubar.add_cascade(label='File', menu=filemenu) 23 filemenu.add_command(label='New', command=do_job) 24 filemenu.add_command(label='Open', command=do_job) 25 filemenu.add_command(label='Save', command=do_job) 26 filemenu.add_separator() 27 filemenu.add_command(label='Exit',command=root.quit) 28 29 editmenu = tk.Menu(menubar, tearoff=0) 30 menubar.add_cascade(label='Edit', menu=editmenu) 31 editmenu.add_command(label='Cut', command=do_job) 32 editmenu.add_command(label='Copy', command=do_job) 33 editmenu.add_command(label='Paste', command=do_job) 34 35 submenu = tk.Menu(filemenu) 36 filemenu.add_cascade(label='Import', menu=submenu, underline=0) 37 submenu.add_command(label='Submenu1', command=do_job) 38 39 root.config(menu = menubar) #將整個menubar添加到窗口 40 root.mainloop()
參數: tearoff 分窗,0爲在原窗,1爲點擊分爲兩個窗口 bg,fg 背景,前景 borderwidth 邊框寬度 font 字體 activebackgound 點擊時背景,一樣有activeforeground,activeborderwidth,disabledforeground cursor postcommand selectcolor 選中時背景 takefocus title type relief 方法: menu.add_cascade 添加子選項 menu.add_command 添加命令(label參數爲顯示內容) menu.add_separator 添加分隔線 menu.add_checkbutton 添加確認按鈕 delete 刪除
1 # -*- coding: utf-8 -*- 2 # @Time : 2018/4/1 20:11 3 # @Author : TanRong 4 # @Software: PyCharm 5 # @File : frame.py 6 import tkinter as tk 7 8 root = tk.Tk() 9 root.title("Frame") 10 root.geometry('400x300') 11 12 tk.Label(root, text='on the window').pack() 13 frm = tk.Frame(root) 14 frm.pack() 15 frm_l = tk.Frame(frm) 16 frm_r = tk.Frame(frm) 17 frm_l.pack(side='left') #固定到左側(是針對父級的,不是主窗口) 18 frm_r.pack(side='right') 19 20 tk.Label(frm_l, text='on the frm_11').pack() 21 tk.Label(frm_l, text='on the frm_12').pack() 22 tk.Label(frm_r, text='on the frm_r').pack() 23 24 root.mainloop()
1 # -*- coding: utf-8 -*- 2 # @Time : 2018/4/1 20:19 3 # @Author : TanRong 4 # @Software: PyCharm 5 # @File : messagebox.py 6 import tkinter as tk 7 import tkinter.messagebox # messagebox必須加這行 8 9 root = tk.Tk() 10 root.title("messagebox") 11 root.geometry('400x300') 12 13 def hit_me(): 14 # tk.messagebox.showinfo(title='Hi', message='hahahha') 15 # tk.messagebox.showwarning(title='Warning', message='nononon') 16 # tk.messagebox.showerror(title='Error', message='fatal! never!!') 17 # print(tk.messagebox.askquestion(title='Hi', message='nononon')) #return 'yes' / 'no' 18 # print(tk.messagebox.askyesno(title='Hi', message='nononon')) # return True / False 19 # print(tk.messagebox.askretrycancel(title='Hi', message='nononon')) # return True / False 20 print(tk.messagebox.askokcancel(title='Hi', message='nononon')) # return True / False 21 22 tk.Button(root, text='hit me', command=hit_me).pack() 23 24 root.mainloop()
messagebox._show函數的控制參數: default 指定消息框按鈕; icon 指定消息框圖標; message 指定消息框所顯示的消息; parent 指定消息框的父組件; title 標題; type 類型; simpledialog模塊參數: title 指定對話框的標題; prompt 顯示的文字; initialvalue 指定輸入框的初始值; filedialog 模塊參數: filetype 指定文件類型; initialdir 指定默認目錄; initialfile 指定默認文件; title 指定對話框標題 colorchooser模塊參數: initialcolor 指定初始化顏色; title 指定對話框標題;
1 # -*- coding: utf-8 -*- 2 # @Time : 2018/4/2 0:50 3 # @Author : TanRong 4 # @Software: PyCharm 5 # @File : pack_grid_place.py 6 import tkinter as tk 7 8 root = tk.Tk() 9 root.title("pack & grid & place") 10 root.geometry('400x300') 11 12 # tk.Label(root, text=1).pack(side='top') 13 # tk.Label(root, text=2).pack(side='bottom') 14 # tk.Label(root, text=3).pack(side='left') 15 # tk.Label(root, text=4).pack(side='right') 16 17 # for i in range(4): 18 # for j in range(3): 19 # tk.Label(root, text=1).grid(row=i, column=j, ipadx=10, ipady=10) #padx和pady是外部的x和y方向的擴展長度,ipadx和ipady是內部的 20 21 tk.Label(root, text=1).place(x=10, y=100, anchor='nw') 22 23 root.mainloop()
bind(sequence,func,add)—— bind_class(className,sequence,func,add) bind_all(sequence,func,add) 事件參數: sequence 所綁定的事件; func 所綁定的事件處理函數; add 可選參數,爲空字符或‘+’; className 所綁定的類; 鼠標鍵盤事件 <Button-1> 鼠標左鍵按下,2表示中鍵,3表示右鍵; <ButtonPress-1> 同上; <ButtonRelease-1> 鼠標左鍵釋放; <B1-Motion> 按住鼠標左鍵移動; <Double-Button-1> 雙擊左鍵; <Enter> 鼠標指針進入某一組件區域; <Leave> 鼠標指針離開某一組件區域; <MouseWheel> 滾動滾輪; <KeyPress-A> 按下A鍵,A可用其餘鍵替代; <Alt-KeyPress-A> 同時按下alt和A;alt可用ctrl和shift替代; <Double-KeyPress-A> 快速按兩下A; <Lock-KeyPress-A> 大寫狀態下按A; 窗口事件 Activate 當組件由不可用轉爲可用時觸發; Configure 當組件大小改變時觸發; Deactivate 當組件由可用轉變爲不可用時觸發; Destroy 當組件被銷燬時觸發; Expose 當組件從被遮擋狀態中暴露出來時觸發; Unmap 當組件由顯示狀態變爲隱藏狀態時觸發; Map 當組件由隱藏狀態變爲顯示狀態時觸發; FocusIn 當組件得到焦點時觸發; FocusOut 當組件失去焦點時觸發; Property 當窗體的屬性被刪除或改變時觸發; Visibility 當組件變爲可視狀態時觸發; 響應事件 event對象(def function(event)): char 按鍵字符,僅對鍵盤事件有效; keycode 按鍵名,僅對鍵盤事件有效; keysym 按鍵編碼,僅對鍵盤事件有效; num 鼠標按鍵,僅對鼠標事件有效; type 所觸發的事件類型; widget 引發事件的組件; width,heigh 組件改變後的大小,僅Configure有效; x,y 鼠標當前位置,相對於窗口; x_root,y_root 鼠標當前位置,相對於整個屏幕
通常格式: ('Times -10 bold') ('Times',10,'bold','italic') 依次表示字體、字號、加粗、傾斜 補充: config 從新配置 label.config(font='Arial -%d bold' % scale.get()) 依次爲字體,大小(大小可爲字號大小),加粗 tkinter.StringVar 能自動刷新的字符串變量,可用set和get方法進行傳值和取值,相似的還有IntVar,DoubleVar...
import tkinter as tk from tkinter import ttk #必須加這個 def select_algorithm(*args): global algo_selected algo_selected = algorithm_combobox.get() print(algo_selected) algo_name = tk.StringVar() algorithm_combobox = ttk.Combobox(tools_frm, textvariable=algo_name, width=12) algorithm_combobox['value'] = ('選擇算法', 'Classification', 'Clustering', 'Regression', 'Projections', 'Dynamical', 'Optimization') #'Reinforcenment Learning' algorithm_combobox['state'] = 'readonly' algorithm_combobox.current(0) algorithm_combobox.bind("<<ComboboxSelected>>", select_algorithm) #添加選擇事件 algorithm_combobox.grid(row=1, column=4)
import tkinter as tk import tkinter.filedialog #必須加 filename = tk.filedialog.askopenfilename(title='選擇訓練數據', filetypes=[('csv','*.csv')]) # print(filename) if len(filename) != 0: data = np.loadtxt(filename, delimiter=',') # 訓練數據
1 # -*- coding: utf-8 -*- 2 # @Time : 2018/4/2 1:00 3 # @Author : TanRong 4 # @Software: PyCharm 5 # @File : login.py 6 import tkinter as tk 7 import pickle 8 import tkinter.messagebox 9 10 root = tk.Tk() 11 root.title('Welcome to Login') 12 root.geometry('450x300') 13 14 # welcome image 15 canvas = tk.Canvas(root, height=200, width=500) 16 image_file = tk.PhotoImage(file='../images/welcome.gif') 17 image = canvas.create_image(0,0, anchor='nw', image=image_file) 18 canvas.pack(side='top') 19 20 #輸入框 21 tk.Label(root, text='User name:').place(x=50, y=150) 22 tk.Label(root, text='Password:').place(x=50, y=190) 23 24 var_usr_name = tk.StringVar() 25 var_usr_pwd = tk.StringVar() 26 var_usr_name.set('loginPython@163.com') 27 28 entry_usr_name = tk.Entry(root, textvariable=var_usr_name) 29 entry_usr_name.place(x=160, y=150) 30 entry_usr_pwd = tk.Entry(root, textvariable=var_usr_pwd, show='*') 31 entry_usr_pwd.place(x=160, y=190) 32 33 def usr_login(): 34 usr_name = var_usr_name.get() 35 usr_pwd = var_usr_pwd.get() 36 try: 37 with open('usrs_info.pickle', 'rb') as usr_file: 38 usrs_info = pickle.load(usr_file) 39 except FileNotFoundError: 40 with open('usrs_info.pickle', 'wb') as usr_file: 41 usrs_info = {'admin':'admin'} #設置管理員信息 42 pickle.dump(usrs_info, usr_file) 43 44 if usr_name in usrs_info: 45 if usr_pwd == usrs_info[usr_name]: 46 tk.messagebox.showinfo(title='Welcome', message='How are you? '+ usr_name) 47 else: 48 tk.messagebox.showerror(title='Error', message='Error your password is wrong, try agein.') 49 else: 50 is_sign_up = tk.messagebox.askyesno(title='Welcome', 51 message='You have not sign up. Sign up today?') 52 if is_sign_up: 53 usr_sign_up() 54 def usr_sign_up(): 55 def sign_to_python(): 56 nname = new_name.get() 57 npwd = new_pwd.get() 58 npwd_confirm = new_pwd_confirm.get() 59 with open('usrs_info.pickle', 'rb') as usr_file: 60 exist_usr_info = pickle.load(usr_file) 61 if npwd != npwd_confirm: 62 tk.messagebox.showerror(title='Error', message='Password and Confirm Password must be same!') 63 elif nname in exist_usr_info: 64 tk.messagebox.showerror(title='Error', message='The user has already signed up!') 65 else: 66 exist_usr_info[nname] = npwd 67 with open('usrs_info.pickle', 'wb') as usr_file: 68 pickle.dump(exist_usr_info, usr_file) 69 tk.messagebox.showinfo(title='Welcome', message='You have successfully signed up!') 70 # global var_usr_name 無效 71 # global var_usr_pwd 72 # var_usr_name = nname 73 # var_usr_pwd = '' 74 window_sign_up.destroy() 75 76 window_sign_up = tk.Toplevel(root) 77 window_sign_up.geometry('350x200') 78 window_sign_up.title('Sign up window') 79 80 new_name = tk.StringVar() 81 new_name.set('loginPython@163.com') 82 tk.Label(window_sign_up, text='User name:').place(x=10, y=10) 83 entry_new_name = tk.Entry(window_sign_up, textvariable=new_name) 84 entry_new_name.place(x=150, y=10) 85 86 new_pwd = tk.StringVar() 87 tk.Label(window_sign_up, text='Password:').place(x=10, y=50) 88 entry_new_pwd = tk.Entry(window_sign_up, textvariable=new_pwd) 89 entry_new_pwd.place(x=150, y=50) 90 91 new_pwd_confirm = tk.StringVar() 92 tk.Label(window_sign_up, text='Confirm Password:').place(x=10, y=90) 93 entry_usr_pwd_confirm = tk.Entry(window_sign_up, textvariable=new_pwd_confirm) 94 entry_usr_pwd_confirm.place(x=150, y=90) 95 96 btn_confirm_sign_up = tk.Button(window_sign_up, text='Sign up', command=sign_to_python) 97 btn_confirm_sign_up.place(x=150, y=130) 98 btn_login = tk.Button(root, text='Login', command=usr_login) 99 btn_login.place(x=170, y=230) 100 btn_sign_up = tk.Button(root, text='Sign up', command=usr_sign_up) 101 btn_sign_up.place(x=270, y=230) 102 103 root.mainloop()
#filename:Caculater import tkinter,time,decimal,math,string root=tkinter.Tk() root.title('計算器') root.resizable(0,0) global cuncu, vartext, result, fuhao result = fuhao = None vartext = tkinter.StringVar() cuncu = [] class anjianzhi: global cuncu, vartext, result, fuhao def __init__(self,anjian): self.anjian = anjian def jia(self): cuncu.append(self.anjian) vartext.set( ''.join(cuncu)) def tui(self): cuncu.pop() vartext.set(''.join(cuncu)) def clear(self): cuncu.clear() vartext.set('') result = None fuhao = None def zhengfu(self): if cuncu[0]: if cuncu[0] == '-': cuncu[0] = '+' elif cuncu[0] == '+': cuncu[0] = '-' else: cuncu.insert(0, '-') vartext.set(''.join(cuncu)) def xiaoshudian(self): if cuncu.count('.') >= 1: pass else: if cuncu == [] : cuncu.append('0') cuncu.append('.') vartext.set(''.join(cuncu)) def yunshuan(self): global cuncu, vartext, result, fuhao if vartext.get() == '': pass else: get1 = decimal.Decimal(vartext.get()) if self.anjian in ('1/x','sqrt'): if self.anjian == '1/x': result = 1/get1 elif self.anjian == 'sqrt': result = math.sqrt(get1) elif self.anjian in ('+','-','*','/','='): if fuhao is not None: get1 = decimal.Decimal(result) get2 = decimal.Decimal(vartext.get()) if fuhao == '+': result = get1 + get2 elif fuhao == '-': result = get1 - get2 elif fuhao == '*': result = get1 * get2 elif fuhao == '/': result = get1 / get2 else: result = get1 if self.anjian == '=': fuhao = None else: fuhao = self.anjian print(fuhao) print(result) vartext.set(str(result)) cuncu.clear() def copy1(): # tkinter.Misc().clipboard_clear() tkinter.Misc().clipboard_append(string(vartext.get())) def buju(root): global cuncu, vartext, result, fuhao entry1 = tkinter.Label(root, width=30, height=2, bg='white', anchor='se', textvariable=vartext) entry1.grid(row=0, columnspan=5) buttonMC=tkinter.Button(root,text='MC',width=5) buttonMR=tkinter.Button(root,text='MR',width=5) buttonMS=tkinter.Button(root,text='MS',width=5) buttonM1=tkinter.Button(root,text='M+',width=5) buttonM2=tkinter.Button(root,text='M-',width=5) buttonMC.grid(row=1,column=0) buttonMR.grid(row=1,column=1) buttonMS.grid(row=1,column=2) buttonM1.grid(row=1,column=3) buttonM2.grid(row=1,column=4) buttonJ=tkinter.Button(root,text='←',width=5,command=anjianzhi('c').tui) buttonCE=tkinter.Button(root,text='CE',width=5) buttonC=tkinter.Button(root,text=' C ',width=5,command=anjianzhi('c').clear) button12=tkinter.Button(root,text='±',width=5,command=anjianzhi('c').zhengfu) buttonD=tkinter.Button(root,text='√',width=5,command=anjianzhi('sqrt').yunshuan) buttonJ.grid(row=2,column=0) buttonCE.grid(row=2,column=1) buttonC.grid(row=2,column=2) button12.grid(row=2,column=3) buttonD.grid(row=2,column=4) button7=tkinter.Button(root,text=' 7 ',width=5,command=anjianzhi('7').jia) button8=tkinter.Button(root,text=' 8 ',width=5,command=anjianzhi('8').jia) button9=tkinter.Button(root,text=' 9 ',width=5,command=anjianzhi('9').jia) buttonc=tkinter.Button(root, text=' / ',width=5,command=anjianzhi('/').yunshuan) buttonf= tkinter.Button(root, text=' % ',width=5) button7.grid(row=3,column=0) button8.grid(row=3,column=1) button9.grid(row=3,column=2) buttonc.grid(row=3,column=3) buttonf.grid(row=3,column=4) button4=tkinter.Button(root,text=' 4 ',width=5,command=anjianzhi('4').jia) button5=tkinter.Button(root,text=' 5 ',width=5,command=anjianzhi('5').jia) button6=tkinter.Button(root,text=' 6 ',width=5,command=anjianzhi('6').jia) buttonx=tkinter.Button(root,text=' * ',width=5,command=anjianzhi('*').yunshuan) buttonfs=tkinter.Button(root,text='1/x',width=5,command=anjianzhi('1/x').yunshuan) button4.grid(row=4,column=0) button5.grid(row=4,column=1) button6.grid(row=4,column=2) buttonx.grid(row=4,column=3) buttonfs.grid(row=4,column=4) button1 = tkinter.Button(root, text=' 1 ',width=5,command=anjianzhi('1').jia) button2 = tkinter.Button(root, text=' 2 ',width=5,command=anjianzhi('2').jia) button3 = tkinter.Button(root, text=' 3 ',width=5,command=anjianzhi('3').jia) button_= tkinter.Button(root, text=' - ',width=5,command=anjianzhi('-').yunshuan) buttondy= tkinter.Button(root, text=' \n = \n ',width=5,command=anjianzhi('=').yunshuan) button1.grid(row=5, column=0) button2.grid(row=5, column=1) button3.grid(row=5, column=2) button_.grid(row=5, column=3) buttondy.grid(row=5, column=4,rowspan=2) button0=tkinter.Button(root,text=' 0 ',width=11,command=anjianzhi('0').jia) buttonjh = tkinter.Button(root,text=' . ',width=5,command=anjianzhi('c').xiaoshudian) buttonjia=tkinter.Button(root,text=' + ',width=5,command=anjianzhi('+').yunshuan) button0.grid(row=6,column=0,columnspan=2) buttonjh.grid(row=6,column=2) buttonjia.grid(row=6,column=3) def caidan(root): menu=tkinter.Menu(root) submenu1=tkinter.Menu(menu,tearoff=0) menu.add_cascade(label='查看',menu=submenu1) submenu2 = tkinter.Menu(menu, tearoff=0) submenu2.add_command(label='複製') submenu2.add_command(label='粘貼') menu.add_cascade(label='編輯',menu=submenu2) submenu = tkinter.Menu(menu, tearoff=0) submenu.add_command(label='查看幫助') submenu.add_separator() submenu.add_command(label='關於計算機') menu.add_cascade(label='幫助',menu=submenu) root.config(menu=menu) buju(root) caidan(root) root.mainloop() 計算器
參考連接: tkinter模塊經常使用參數(python3):http://www.cnblogs.com/aland-1415/p/6849193.html