python tkinter(2)

1、設(shè)置label的字體、顏色、背景色努酸、寬、高
from tkinter import *
root = Tk()
labelfont = ('times', 20, 'bold') # family, size, style
widget = Label(root, text='Hello config world')
widget.config(bg='black', fg='yellow') # yellow text on black label
widget.config(font=labelfont) # use a larger font
widget.config(height=3, width=20) # initial size: lines,chars
widget.pack(expand=YES, fill=BOTH)
root.mainloop()
2杜恰、bd設(shè)置邊框获诈、relief=設(shè)置邊框類型,cursor鼠標(biāo)


image.png

3心褐、設(shè)置BUTTON的邊框舔涎、邊框類型、鼠標(biāo)逗爹、字體等
from tkinter import *
widget = Button(text='Spam', padx=10, pady=10)
widget.pack(padx=20, pady=20)
widget.config(cursor='gumby')
widget.config(bd=8, relief=RAISED)
widget.config(bg='dark green', fg='white')
widget.config(font=('helvetica', 20, 'underline italic'))
mainloop()
4亡嫌、三個窗口
import sys
from tkinter import Toplevel, Button, Label

win1 = Toplevel() # two independent windows
win2 = Toplevel() # but part of same process

Button(win1, text='Spam', command=sys.exit).pack()
Button(win2, text='SPAM', command=sys.exit).pack()

Label(text='Popups').pack() # on default Tk() root window
win1.mainloop()
5、創(chuàng)建兩個窗口桶至,不要顯示根窗口
import tkinter
from tkinter import Tk, Button
tkinter.NoDefaultRoot()

win1 = Tk() # two independent root windows
win2 = Tk()

Button(win1, text='Spam', command=win1.destroy).pack()
Button(win2, text='SPAM', command=win2.destroy).pack()
win1.mainloop()
6昼伴、Tk()根窗口匾旭,Toplevel(root)子窗口镣屹,protocol('WM_DELETE_WINDOW',lambda:None)點關(guān)閉按鈕無效,iconbitmap窗口圖標(biāo),root.quit
from tkinter import *
root = Tk() # explicit root

trees = [('The Larch!', 'light blue'),
('The Pine!', 'light green'),
('The Giant Redwood!', 'red')]

for (tree, color) in trees:
win = Toplevel(root) # new window
win.title('Sing...') # set border
win.protocol('WM_DELETE_WINDOW', lambda:None) # ignore close

win.iconbitmap('py-blue-trans-out.ico') # not red Tk

msg = Button(win, text=tree, command=win.destroy)           # kills one win
msg.pack(expand=YES, fill=BOTH)
msg.config(padx=10, pady=10, bd=10, relief=RAISED)
msg.config(bg='black', fg=color, font=('times', 30, 'bold italic'))

root.title('Lumberjack demo')
Label(root, text='Main window', width=30).pack()
Button(root, text='Quit All', command=root.quit).pack() # kills all app
root.mainloop()
7价涝、窗口狀態(tài)


image.png

8女蜈、子窗口獲得根窗口
theframe.master.xxxx
9、
"""
pop up three new windows, with style
destroy() kills one window, quit() kills all windows and app (ends mainloop);
top-level windows have title, icon, iconify/deiconify and protocol for wm events;
there always is an application root window, whether by default or created as an
explicit Tk() object; all top-level windows are containers, but they are never
packed/gridded; Toplevel is like Frame, but a new window, and can have a menu;
"""

from tkinter import *
from tkinter.messagebox import *

def callback():
if askyesno('Verify', 'Do you really want to quit?'):
showwarning('Yes', 'Quit not yet implemented')
else:
showinfo('No', 'Quit has been cancelled')

errmsg = 'Sorry, no Spam allowed!'
Button(text='Quit', command=callback).pack(fill=X)
Button(text='Spam', command=(lambda: showerror('Spam', errmsg))).pack(fill=X)
mainloop()
showerror,showwarning,showinfo,askyesno,askyesno
10色瘩、askopenfilename ,askcolor,askquestion,showerror,askfloat
"""
a Quit button that verifies exit requests;
to reuse, attach an instance to other GUIs, and re-pack as desired
"""

from tkinter import * # get widget classes
from tkinter.messagebox import askokcancel # get canned std dialog

class Quitter(Frame): # subclass our GUI
def init(self, parent=None): # constructor method
Frame.init(self, parent)
self.pack()
widget = Button(self, text='Quit', command=self.quit)
widget.pack(side=LEFT, expand=YES, fill=BOTH)

def quit(self):
    ans = askokcancel('Verify exit', "Really quit?")
    if ans: Frame.quit(self)

if name == 'main': Quitter().mainloop()

define a name:callback demos table

from tkinter.filedialog import askopenfilename # get standard dialogs
from tkinter.colorchooser import askcolor # they live in Lib\tkinter
from tkinter.messagebox import askquestion, showerror
from tkinter.simpledialog import askfloat

demos = {
'Open': askopenfilename,
'Color': askcolor,
'Query': lambda: askquestion('Warning', 'You typed "rm *"\nConfirm?'),
'Error': lambda: showerror('Error!', "He's dead, Jim"),
'Input': lambda: askfloat('Entry', 'Enter credit card number')
}

"create a bar of simple buttons that launch dialog demos"

from tkinter import * # get base widget set

class Demo(Frame):
def init(self, parent=None, **options):
Frame.init(self, parent, **options)
self.pack()
Label(self, text="Basic demos").pack()
for (key, value) in demos.items():
Button(self, text=key, command=value).pack(side=TOP, fill=BOTH)
Quitter(self).pack(side=TOP, fill=BOTH)

if name == 'main': Demo().mainloop()
11伪窖、彈出框,設(shè)置背景顏色
from tkinter import *
from tkinter.colorchooser import askcolor

def setBgColor():
(triple, hexstr) = askcolor()
if hexstr:
print(hexstr)
push.config(bg=hexstr)

root = Tk()
push = Button(root, text='Set Background Color', command=setBgColor)
push.config(height=3, font=('times', 20, 'bold'))
push.pack(expand=YES, fill=BOTH)
root.mainloop()
12居兆、win.focus_set(),grab_set
import sys
from tkinter import *
makemodal = (len(sys.argv) > 1)

def dialog():
win = Toplevel() # make a new window
Label(win, text='Hard drive reformatted!').pack() # add a few widgets
Button(win, text='OK', command=win.destroy).pack() # set destroy callback
if makemodal:
win.focus_set() # take over input focus,
win.grab_set() # disable other windows while I'm open,
win.wait_window() # and wait here until win destroyed
print('dialog exit') # else returns right away

root = Tk()
Button(root, text='popup', command=dialog).pack()
root.mainloop()
13覆山、
from tkinter import *
msg = Message(text="Oh by the way, which one's Pink?")
msg.config(bg='pink', font=('times', 16, 'italic'))
msg.pack(fill=X, expand=YES)
mainloop()
14、
from tkinter import *
from quitter import Quitter

def fetch():
print('Input => "%s"' % ent.get()) # get text

root = Tk()
ent = Entry(root)
ent.insert(0, 'Type words here') # set text
ent.pack(side=TOP, fill=X) # grow horiz

ent.focus() # save a click
ent.bind('<Return>', (lambda event: fetch())) # on enter key
btn = Button(root, text='Fetch', command=fetch) # and on button
btn.pack(side=LEFT)
Quitter(root).pack(side=RIGHT)
root.mainloop()
////////Entry
15泥栖、設(shè)置模態(tài):


image.png

16簇宽、

check buttons, the hard way (without variables)

from tkinter import *
states = [] # change object not name
def onPress(i): # keep track of states
states[i] = not states[i] # changes False->True, True->False

root = Tk()
for i in range(10):
chk = Checkbutton(root, text=str(i), command=(lambda i=i: onPress(i)) )
chk.pack(side=LEFT)
states.append(False)
root.mainloop()
print(states) # show all states on exit
17\ intvar???

check buttons, the easy way

from tkinter import *
root = Tk()
states = []
for i in range(10):
var = IntVar()
chk = Checkbutton(root, text=str(i), variable=var)
chk.pack(side=LEFT)
states.append(var)
root.mainloop() # let tkinter keep track
print([var.get() for var in states]) # show all states on exit (or map/lambda)

alternatives

print(list(map(IntVar.get, states)))

print(list(map(lambda var: var.get(), states)))

18、
"""
4 demo class components (subframes) on one window;
there are 5 Quitter buttons on this one window too, and each kills entire gui;
GUIs can be reused as frames in container, independent windows, or processes;
"""

from tkinter import *
from quitter import Quitter
demoModules = ['demoDlg', 'demoCheck', 'demoRadio', 'demoScale']
parts = []

def addComponents(root):
for demo in demoModules:
module = import(demo) # import by name string
part = module.Demo(root) # attach an instance
part.config(bd=2, relief=GROOVE) # or pass configs to Demo()
part.pack(side=LEFT, expand=YES, fill=BOTH) # grow, stretch with window
parts.append(part) # change list in-place

def dumpState():
for part in parts: # run demo report if any
print(part.module + ':', end=' ')
if hasattr(part, 'report'):
part.report()
else:
print('none')

root = Tk() # make explicit root first
root.title('Frames')
Label(root, text='Multiple Frame demo', bg='white').pack()
Button(root, text='States', command=dumpState).pack(fill=X)
Quitter(root).pack(fill=X)
addComponents(root)
root.mainloop()
19\ imagebutton
gifdir = "../gifs/"
from tkinter import *
win = Tk()
igm = PhotoImage(file=gifdir + "ora-pp.gif")
Button(win, image=igm).pack()
win.mainloop()
20
gifdir = "../gifs/"
from tkinter import *
win = Tk()
img = PhotoImage(file=gifdir + "ora-lp4e.gif")
can = Canvas(win)
can.pack(fill=BOTH)
can.create_image(2, 2, image=img, anchor=NW) # x, y coordinates
win.mainloop()
21\ PIL處理圖像


image.png

22吧享、pil
"""
show one image with PIL photo replacement object
handles many more image types; install PIL first: placed in Lib\site-packages
"""

import os, sys
from tkinter import *
from PIL.ImageTk import PhotoImage # <== use PIL replacement class
# rest of code unchanged
imgdir = 'images'
imgfile = 'florida-2009-1.jpg' # does gif, jpg, png, tiff, etc.
if len(sys.argv) > 1:
imgfile = sys.argv[1]
imgpath = os.path.join(imgdir, imgfile)

win = Tk()
win.title(imgfile)
imgobj = PhotoImage(file=imgpath) # now JPEGs work!
Label(win, image=imgobj).pack()
win.mainloop()
print(imgobj.width(), imgobj.height()) # show size in pixels on exit
23 pil 顯示目錄下所有圖片
"""
display all images in a directory in pop-up windows
GIFs work in basic tkinter, but JPEGs will be skipped without PIL
"""

import os, sys
from tkinter import *
from PIL.ImageTk import PhotoImage # <== required for JPEGs and others

imgdir = 'images'
if len(sys.argv) > 1: imgdir = sys.argv[1]
imgfiles = os.listdir(imgdir) # does not include directory prefix

main = Tk()
main.title('Viewer')
quit = Button(main, text='Quit all', command=main.quit, font=('courier', 25))
quit.pack()
savephotos = []

for imgfile in imgfiles:
imgpath = os.path.join(imgdir, imgfile)
win = Toplevel()
win.title(imgfile)
try:
imgobj = PhotoImage(file=imgpath)
Label(win, image=imgobj).pack()
print(imgpath, imgobj.width(), imgobj.height()) # size in pixels
savephotos.append(imgobj) # keep a reference
except:
errmsg = 'skipping %s\n%s' % (imgfile, sys.exc_info()[1])
Label(win, text=errmsg).pack()

main.mainloop()
24

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末魏割,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子钢颂,更是在濱河造成了極大的恐慌钞它,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,214評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異遭垛,居然都是意外死亡尼桶,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,307評論 2 382
  • 文/潘曉璐 我一進店門锯仪,熙熙樓的掌柜王于貴愁眉苦臉地迎上來疯汁,“玉大人,你說我怎么就攤上這事卵酪』衔茫” “怎么了?”我有些...
    開封第一講書人閱讀 152,543評論 0 341
  • 文/不壞的土叔 我叫張陵溃卡,是天一觀的道長溢豆。 經(jīng)常有香客問我,道長瘸羡,這世上最難降的妖魔是什么漩仙? 我笑而不...
    開封第一講書人閱讀 55,221評論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮犹赖,結(jié)果婚禮上队他,老公的妹妹穿的比我還像新娘。我一直安慰自己峻村,他們只是感情好麸折,可當(dāng)我...
    茶點故事閱讀 64,224評論 5 371
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著粘昨,像睡著了一般垢啼。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上张肾,一...
    開封第一講書人閱讀 49,007評論 1 284
  • 那天芭析,我揣著相機與錄音,去河邊找鬼吞瞪。 笑死馁启,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的芍秆。 我是一名探鬼主播惯疙,決...
    沈念sama閱讀 38,313評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼浪听!你這毒婦竟也來了螟碎?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 36,956評論 0 259
  • 序言:老撾萬榮一對情侶失蹤迹栓,失蹤者是張志新(化名)和其女友劉穎掉分,沒想到半個月后俭缓,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,441評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡酥郭,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,925評論 2 323
  • 正文 我和宋清朗相戀三年华坦,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片不从。...
    茶點故事閱讀 38,018評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡惜姐,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出椿息,到底是詐尸還是另有隱情歹袁,我是刑警寧澤,帶...
    沈念sama閱讀 33,685評論 4 322
  • 正文 年R本政府宣布寝优,位于F島的核電站玩裙,受9級特大地震影響魄健,放射性物質(zhì)發(fā)生泄漏拭荤。R本人自食惡果不足惜润匙,卻給世界環(huán)境...
    茶點故事閱讀 39,234評論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望钻心。 院中可真熱鬧凄硼,春花似錦、人聲如沸捷沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,240評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽亿胸。三九已至坯钦,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間侈玄,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,464評論 1 261
  • 我被黑心中介騙來泰國打工吟温, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留序仙,地道東北人。 一個月前我還...
    沈念sama閱讀 45,467評論 2 352
  • 正文 我出身青樓鲁豪,卻偏偏與公主長得像潘悼,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子爬橡,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 42,762評論 2 345

推薦閱讀更多精彩內(nèi)容