前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python tkinter(2)

python tkinter(2)

作者头像
用户5760343
发布2022-05-13 10:51:29
7580
发布2022-05-13 10:51:29
举报
文章被收录于专栏:sktjsktj

1、设置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设置边框、relief=设置边框类型,cursor鼠标

image.png

3、设置BUTTON的边框、边框类型、鼠标、字体等 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、创建两个窗口,不要显示根窗口 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)点关闭按钮无效,iconbitmap窗口图标,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

代码语言:javascript
复制
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、窗口状态

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)

代码语言:javascript
复制
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、弹出框,设置背景颜色 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、设置模态:

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-05-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • win.iconbitmap('py-blue-trans-out.ico') # not red Tk
  • define a name:callback demos table
  • check buttons, the hard way (without variables)
  • check buttons, the easy way
  • alternatives
  • print(list(map(IntVar.get, states)))
  • print(list(map(lambda var: var.get(), states)))
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档