您的位置:首页技术文章
文章详情页

python GUI编程(Tkinter) 创建子窗口及在窗口上用图片绘图实例

日期:2022-08-04 10:06:02浏览:9作者:猪猪【字号:
导读:注意主窗口一定要为tk.Tk(),在主窗口上通过button的点击相应子函数创建子窗口,注意此时创建出来的窗口必须是Toplevel,否则出错。至于用图片在窗口上绘图,则按代码所示即可。# -*- coding: utf-8 -*-'''Created on Wed Oct 26 20:32:52 ...

注意主窗口一定要为tk.Tk(),在主窗口上通过button的点击相应子函数创建子窗口,注意此时创建出来的窗口必须是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中出现的坑(界面Tk()+图片显示)

一、关于Python3的tkinter模块

1、首先关于创建Python的窗口是导入 import tkinter 或者 from tkinter import * 这两种形式。关于创建tkinter 的大家耳熟能详的就是直接 win=Tk()[在导入方式为from tkinter import *形式下],但是还有另一种方法用来创建窗口那就是:win=Toplevel(),这个代表的是创建二级界面,就是直接创建两个界面,这个方法非常实用,应用在多个函数调用并生成Python窗口上面。小逸亲自尝试了一下,相当的好哈哈~~~~

2、Toplevel()实际操作。

首先,我们在Python3的环境下写下以下简单的代码:

from tkinter import *win=Toplevel()win.title=('这是一个二级界面')win.geometry('500x300+10+10')win.mainloop()

上面的代码运行后将出现以下的两个窗口:

python GUI编程(Tkinter) 创建子窗口及在窗口上用图片绘图实例

二、# 关于在Label中显示图片的大坑

1、在Label 中显示图片需要用到tkinter 与pillow这两个模块

单独运行一个在tkinter上显示的图片没有问题,但是如果把这个显示图片的函数放在一个Button的command中,那么就算用二级界面也不行了,这个是一个非常大的坑,但是解决方法也非常非常的简单。只要将处理图片的两行代码放在外面就行了。如图:

python GUI编程(Tkinter) 创建子窗口及在窗口上用图片绘图实例

以上这篇python GUI编程(Tkinter) 创建子窗口及在窗口上用图片绘图实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持好吧啦网。

标签: Python 编程
相关文章: