python GUI編程(Tkinter) 創(chuàng)建子窗口及在窗口上用圖片繪圖實例
注意主窗口一定要為tk.Tk(),在主窗口上通過button的點擊相應(yīng)子函數(shù)創(chuàng)建子窗口,注意此時創(chuàng)建出來的窗口必須是Toplevel,否則出錯。
至于用圖片在窗口上繪圖,則按代碼所示即可。
# -*- coding: utf-8 -*- """ Created on Wed Oct 26 20:32:52 2016 @author: min """ import Tkinter as tk from PIL import Image, ImageTk global attackTime attackTime=1 def 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()
補充知識:關(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(),這個代表的是創(chuàng)建二級界面,就是直接創(chuàng)建兩個界面,這個方法非常實用,應(yī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)以下的兩個窗口:
二、# 關(guān)于在Label中顯示圖片的大坑
1、在Label 中顯示圖片需要用到tkinter 與pillow這兩個模塊
單獨運行一個在tkinter上顯示的圖片沒有問題,但是如果把這個顯示圖片的函數(shù)放在一個Button的command中,那么就算用二級界面也不行了,這個是一個非常大的坑,但是解決方法也非常非常的簡單。只要將處理圖片的兩行代碼放在外面就行了。如圖:
以上這篇python GUI編程(Tkinter) 創(chuàng)建子窗口及在窗口上用圖片繪圖實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python使用Faker進行隨機數(shù)據(jù)生成
大家好,本篇文章主要講的是python使用Faker進行隨機數(shù)據(jù)生成,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下2022-02-02Python 編碼規(guī)范(Google Python Style Guide)
本項目并非 Google 官方項目, 而是由國內(nèi)程序員憑熱情創(chuàng)建和維護,對于想學(xué)習python的朋友可以參考一下2018-05-05python實現(xiàn)代碼行數(shù)統(tǒng)計示例分享
這篇文章主要介紹了python實現(xiàn)代碼行數(shù)統(tǒng)計的示例,需要的朋友可以參考下2014-02-02node命令行服務(wù)器(http-server)和跨域的實現(xiàn)
本文主要介紹了node命令行服務(wù)器(http-server)和跨域的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2023-02-02使用 Python 的 pprint庫格式化和輸出列表和字典的方法
pprint是"pretty-print"的縮寫,使用 Python 的標準庫 pprint 模塊,以干凈的格式輸出和顯示列表和字典等對象,這篇文章主要介紹了如何使用 Python 的 pprint庫格式化和輸出列表和字典,需要的朋友可以參考下2023-05-05使用C#配合ArcGIS Engine進行地理信息系統(tǒng)開發(fā)
這篇文章主要介紹了使用C#配合ArcGIS Engine進行地理信息系統(tǒng)開發(fā),ArcGIS Engine是Windows系統(tǒng)上可以讓程序員創(chuàng)建自定義的GIS桌面程序,需要的朋友可以參考下2016-02-02