python GUI編程(Tkinter) 創(chuàng)建子窗口及在窗口上用圖片繪圖實(shí)例
注意主窗口一定要為tk.Tk(),在主窗口上通過button的點(diǎn)擊相應(yīng)子函數(shù)創(chuàng)建子窗口,注意此時(shí)創(chuàng)建出來的窗口必須是Toplevel,否則出錯(cuò)。
至于用圖片在窗口上繪圖,則按代碼所示即可。
# -*- 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()
補(bǔ)充知識(shí):關(guān)于Python tkinter中出現(xiàn)的坑(界面Tk()+圖片顯示)
一、關(guān)于Python3的tkinter模塊
1、首先關(guān)于創(chuàng)建Python的窗口是導(dǎo)入 import tkinter 或者 from tkinter import * 這兩種形式。關(guān)于創(chuàng)建tkinter 的大家耳熟能詳?shù)木褪侵苯?win=Tk()[在導(dǎo)入方式為from tkinter import *形式下],但是還有另一種方法用來創(chuàng)建窗口那就是:win=Toplevel(),這個(gè)代表的是創(chuàng)建二級(jí)界面,就是直接創(chuàng)建兩個(gè)界面,這個(gè)方法非常實(shí)用,應(yīng)用在多個(gè)函數(shù)調(diào)用并生成Python窗口上面。小逸親自嘗試了一下,相當(dāng)?shù)暮霉~~~
2、Toplevel()實(shí)際操作。
首先,我們?cè)赑ython3的環(huán)境下寫下以下簡(jiǎn)單的代碼:
from tkinter import *win=Toplevel()win.title=('這是一個(gè)二級(jí)界面')win.geometry('500x300+10+10')win.mainloop()
上面的代碼運(yùn)行后將出現(xiàn)以下的兩個(gè)窗口:
二、# 關(guān)于在Label中顯示圖片的大坑
1、在Label 中顯示圖片需要用到tkinter 與pillow這兩個(gè)模塊
單獨(dú)運(yùn)行一個(gè)在tkinter上顯示的圖片沒有問題,但是如果把這個(gè)顯示圖片的函數(shù)放在一個(gè)Button的command中,那么就算用二級(jí)界面也不行了,這個(gè)是一個(gè)非常大的坑,但是解決方法也非常非常的簡(jiǎn)單。只要將處理圖片的兩行代碼放在外面就行了。如圖:
以上這篇python GUI編程(Tkinter) 創(chuàng)建子窗口及在窗口上用圖片繪圖實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 解決Android Studio 格式化 Format代碼快捷鍵問題2. php解決注冊(cè)并發(fā)問題并提高QPS3. 完美解決vue 中多個(gè)echarts圖表自適應(yīng)的問題4. 在Chrome DevTools中調(diào)試JavaScript的實(shí)現(xiàn)5. Springboot 全局日期格式化處理的實(shí)現(xiàn)6. SpringBoot+TestNG單元測(cè)試的實(shí)現(xiàn)7. Java使用Tesseract-Ocr識(shí)別數(shù)字8. vue實(shí)現(xiàn)web在線聊天功能9. JS原生2048小游戲源碼分享(全網(wǎng)最新)10. Python使用urlretrieve實(shí)現(xiàn)直接遠(yuǎn)程下載圖片的示例代碼
