Python Tkinter 簡單使用

一清發表於2019-01-19
簡單的一些例項,能夠實現一般的功能就夠用了
Tkinter:
建立頂層視窗:
# -*- coding: utf-8 -*-
from Tkinter import *
 
root = Tk()
root.title(“頂層視窗”)
root.mainloop()
 
Label使用:
# -*- coding: utf-8 -*-
from Tkinter import *
 
root = Tk()
root.title(“頂層視窗”)
label = Label(root, text=”Hello World!”)
label.pack()
root.mainloop()
 
加入一些引數:
# -*- coding: utf-8 -*-
from Tkinter import *
 
root = Tk()
root.title(“頂層視窗”)
label = Label(root, text=”Hello World!”, height=10, width=30, fg=”black”, bg=”pink”)
label.pack()
root.mainloop()
 
Frame:
# -*- coding: utf-8 -*-
from Tkinter import *
 
root = Tk()
root.title(“頂層視窗”)
for relief in [RAISED, SUNKEN, RIDGE, GROOVE, SOLID]:
    f = Frame(root, borderwidth=2, relief=relief)
    Label(f, text=relief, width=10).pack(side=LEFT)
    f.pack(side=LEFT, padx=5, pady=5)
root.mainloop()
 
Button:
# -*- coding: utf-8 -*-
from Tkinter import *
 
root = Tk()
root.title(“頂層視窗”)
Button(root, text=”禁用”, state=DISABLED).pack(side=LEFT)
Button(root, text=”取消”).pack(side=LEFT)
Button(root, text=”確定”).pack(side=LEFT)
Button(root, text=”退出”, command=root.quit).pack(side=RIGHT)
root.mainloop()
 
給按鈕加一些引數:
# -*- coding: utf-8 -*-
from Tkinter import *
 
root = Tk()
root.title(“頂層視窗”)
Button(root, text=”禁用”, state=DISABLED, height=2, width=10).pack(side=LEFT)
Button(root, text=”取消”, height=2, width=10, fg=”red”).pack(side=LEFT)
Button(root, text=”確定”, height=2, width=10, fg=”blue”, activebackground=”blue”, activeforeground=”yellow”).pack(
    side=LEFT)
Button(root, text=”退出”, command=root.quit, fg=”black”, height=2, width=10).pack(side=RIGHT)
root.mainloop()
 
Entry:
# -*- coding: utf-8 -*-
from Tkinter import *
 
root = Tk()
root.title(“頂層視窗”)
 
f1 = Frame(root)
Label(f1, text=”標準輸入框:”).pack(side=LEFT, padx=5, pady=10)
e1 = StringVar()
Entry(f1, width=50, textvariable=e1).pack(side=LEFT)
e1.set(“請輸入內容”)
f1.pack()
 
f2 = Frame(root)
e2 = StringVar()
Label(f2, text=”禁用輸入框:”).pack(side=LEFT, padx=5, pady=10)
Entry(f2, width=50, textvariable=e2, state=DISABLED).pack(side=LEFT)
e2.set(“不可修改內容”)
f2.pack()
 
root.mainloop()
 
小案例:攝氏度轉為華氏度
# -*- coding: utf-8 -*-
import Tkinter as tk
 
 
def cToFClicked():
    cd = float(entryCd.get())
    labelcToF.config(text=”%.2f攝氏度 = %.2f華氏度” % (cd, cd * 1.8 + 32))
 
 
top = tk.Tk()
top.title(“攝氏度轉華氏度”)
labelcToF = tk.Label(top, text=”攝氏度轉華氏度”, height=5, width=30, fg=”blue”)
labelcToF.pack()
entryCd = tk.Entry(top, text=”0″)
entryCd.pack()
btnCal = tk.Button(top, text=”計算”, command=cToFClicked)
btnCal.pack()
 
top.mainloop()
 
RadioButton:
# -*- coding: utf-8 -*-
from Tkinter import *
 
root = Tk()
root.title(“頂層視窗”)
 
foo = IntVar()
for text, value in [(`red`, 1), (`greed`, 2), (`black`, 3), (`blue`, 4), (`yellow`, 5)]:
    r = Radiobutton(root, text=text, value=value, variable=foo)
    r.pack(anchor=W)
 
foo.set(2)
root.mainloop()
 
CheckButton:
# -*- coding: utf-8 -*-
from Tkinter import *
 
root = Tk()
root.title(“頂層視窗”)
 
l = [(`red`, 1), (`green`, 2), (`black`, 3), (`blue`, 4), (`yellow`, 5)]
for text, value in l:
    foo = IntVar()
    c = Checkbutton(root, text=text, variable=foo)
    c.pack(anchor=W)
 
root.mainloop()
 
其他的東西比如文字框,滾動條
其實類似,這裡就不全部列出來了,其實最常用的也是上面的這些東西
 
下面做一些小案例:
# -*- coding:utf-8 -*-
from Tkinter import *
 
 
class MainWindow:
    def __init__(self):
        self.frame = Tk()
        self.label_name = Label(self.frame, text=”name:”)
        self.label_age = Label(self.frame, text=”age:”)
        self.label_sex = Label(self.frame, text=”sex:”)
        self.text_name = Text(self.frame, height=1, width=30)
        self.text_age = Text(self.frame, height=1, width=30)
        self.text_sex = Text(self.frame, height=1, width=30)
        self.label_name.grid(row=0, column=0)
        self.label_age.grid(row=1, column=0)
        self.label_sex.grid(row=2, column=0)
        self.button_ok = Button(self.frame, text=”ok”, width=10)
        self.button_cancel = Button(self.frame, text=”cancel”, width=10)
        self.text_name.grid(row=0, column=1)
        self.text_age.grid(row=1, column=1)
        self.text_sex.grid(row=2, column=1)
        self.button_ok.grid(row=3, column=0)
        self.button_cancel.grid(row=3, column=1)
        self.frame.mainloop()
 
 
frame = MainWindow()
 
最後一個綜合案例
計算器:
# -*- coding:utf-8 -*-
from Tkinter import *
 
 
def frame(root, side):
    w = Frame(root)
    w.pack(side=side, expand=YES, fill=BOTH)
    return w
 
 
def button(root, side, text, command=None):
    w = Button(root, text=text, command=command)
    w.pack(side=side, expand=YES, fill=BOTH)
    return w
 
 
class Calculator(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.option_add(`*Font`, `Verdana 12 bold`)
        self.pack(expand=YES, fill=BOTH)
        self.master.title(`Simple Cal`)
        self.master.iconname(`calc1`)
 
        display = StringVar()
        Entry(self, relief=SUNKEN, textvariable=display).pack(side=TOP, expand=YES, fill=BOTH)
        for key in (`123`, `456`, `789`, `+0.`):
            keyF = frame(self, TOP)
            for char in key:
                button(keyF, LEFT, char, lambda w=display, c=char: w.set(w.get() + c))
        opsF = frame(self, TOP)
 
        for char in `-*/=`:
            if char == `=`:
                btn = button(opsF, LEFT, char)
                btn.bind(`<ButtonRelease-1>`, lambda e, s=self, w=display: s.calc(w), `+`)
            else:
                btn = button(opsF, LEFT, char, lambda w=display, s=`%s` % char: w.set(w.get() + s))
 
        clearF = frame(self, BOTTOM)
        button(clearF, LEFT, `CLEAR`, lambda w=display: w.set(“))
 
    def calc(self, display):
        try:
            display.set(eval(display.get()))
        except:
            display.set(`ERROR`)
 
 
if __name__ == `__main__`:
    Calculator().mainloop()
 
 

相關文章