python GUI編程(Tkinter) 創(chuàng)建子窗口及在窗口上用圖片繪圖實例
注意主窗口一定要為tk.Tk(),在主窗口上通過button的點擊相應子函數(shù)創(chuàng)建子窗口,注意此時創(chuàng)建出來的窗口必須是Toplevel,否則出錯。
至于用圖片在窗口上繪圖,則按代碼所示即可。
# -*- coding: utf-8 -*-'''Created on Wed Oct 26 20:32:52 2016@author: min'''import Tkinter as tkfrom PIL import Image, ImageTk global attackTimeattackTime=1def show1(): top1=tk.Toplevel() image = Image.open(’random.jpg’) img = ImageTk.PhotoImage(image) canvas1 = tk.Canvas(top1, width = image.width*2 ,height = image.height*2, bg = ’white’) canvas1.create_image(0,0,image = img,anchor='nw') canvas1.create_image(image.width,0,image = img,anchor='nw') canvas1.pack() top1.mainloop()def show2(): top1=tk.Toplevel() image = Image.open(’random.jpg’) img = ImageTk.PhotoImage(image) canvas = tk.Canvas(top1, width = image.width ,height = image.height, bg = ’white’) canvas.create_image(0,0,image = img,anchor='nw') canvas.pack() top1.mainloop()def showMessage(): top=tk.Toplevel() l=tk.Label(top,text=’Attacks cost ’+str(attackTime)+’ s’,width=20) l.pack() top.mainloop() root=tk.Tk()b1=tk.Button(root,text=’start1’,command=show1)b1.pack()b2=tk.Button(root,text=’start2’,command=showMessage)b2.pack()root.mainloop()
補充知識:關于Python tkinter中出現(xiàn)的坑(界面Tk()+圖片顯示)
一、關于Python3的tkinter模塊
1、首先關于創(chuàng)建Python的窗口是導入 import tkinter 或者 from tkinter import * 這兩種形式。關于創(chuàng)建tkinter 的大家耳熟能詳?shù)木褪侵苯?win=Tk()[在導入方式為from tkinter import *形式下],但是還有另一種方法用來創(chuàng)建窗口那就是:win=Toplevel(),這個代表的是創(chuàng)建二級界面,就是直接創(chuàng)建兩個界面,這個方法非常實用,應用在多個函數(shù)調(diào)用并生成Python窗口上面。小逸親自嘗試了一下,相當?shù)暮霉~~~
2、Toplevel()實際操作。
首先,我們在Python3的環(huán)境下寫下以下簡單的代碼:
from tkinter import *win=Toplevel()win.title=('這是一個二級界面')win.geometry('500x300+10+10')win.mainloop()
上面的代碼運行后將出現(xiàn)以下的兩個窗口:
二、# 關于在Label中顯示圖片的大坑
1、在Label 中顯示圖片需要用到tkinter 與pillow這兩個模塊
單獨運行一個在tkinter上顯示的圖片沒有問題,但是如果把這個顯示圖片的函數(shù)放在一個Button的command中,那么就算用二級界面也不行了,這個是一個非常大的坑,但是解決方法也非常非常的簡單。只要將處理圖片的兩行代碼放在外面就行了。如圖:
以上這篇python GUI編程(Tkinter) 創(chuàng)建子窗口及在窗口上用圖片繪圖實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關文章:
1. python實現(xiàn)讀取類別頻數(shù)數(shù)據(jù)畫水平條形圖案例2. python中PyQuery庫用法分享3. python操作數(shù)據(jù)庫獲取結(jié)果之fetchone和fetchall的區(qū)別說明4. Ajax實現(xiàn)頁面無刷新留言效果5. php5.6不能擴展redis.so的解決方法6. JSP+Servlet實現(xiàn)文件上傳到服務器功能7. 阿里前端開發(fā)中的規(guī)范要求8. 關于HTML5的img標簽9. CSS3實現(xiàn)動態(tài)翻牌效果 仿百度貼吧3D翻牌一次動畫特效10. PHP獲取時間戳等相關函數(shù)匯總
