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 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()
補充知識:關于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ù)調用并生成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)建子窗口及在窗口上用圖片繪圖實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python threading Local()函數(shù)用法案例詳解
這篇文章主要介紹了Python threading Local()函數(shù)用法案例詳解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下2021-09-09
Python使用Matplotlib和Seaborn繪制常用圖表的技巧
Python作為數(shù)據(jù)科學領域的明星語言,擁有強大且豐富的可視化庫,其中最著名的莫過于 Matplotlib 和 Seaborn,本篇博客將作為數(shù)據(jù)可視化之旅的起點,手把手帶領完全新手讀者,從零開始學習如何使用Matplotlib和Seaborn繪制常用圖表,需要的朋友可以參考下2025-12-12
python 數(shù)字轉換為日期的三種實現(xiàn)方法
在Python中,我們經(jīng)常需要處理日期和時間,本文主要介紹了python 數(shù)字轉換為日期的三種實現(xiàn)方法,包含datetime模塊,strftime方法及pandas庫,具有一定的參考價值,感興趣的可以了解一下2024-02-02

