个性化阅读
专注于IT技术分析

Python在Tkinter按钮上添加图像

Tkinter是一个Python模块, 用于借助各种小部件和功能来创建GUI(图形用户界面)应用程序。像任何其他GUI模块一样, 它也支持图像, 即你可以在应用程序中使用图像以使其更具吸引力。

图像可以借助PhotoImage()方法。这是Tkinter方法, 这意味着你无需导入任何其他模块即可使用它。

重要:如果同时提供图片和文字纽扣, 文字将占主导地位, 并且仅图像会出现在Button上。但是, 如果要同时显示图像和文本, 则必须通过复合在按钮选项中。

Button(主键, 文本=” Button”, 图像=” image.png”, 复合=左)复合=左->图像位于按钮复合的左侧= RIGHT->图像位于按钮复合的右侧=顶部->图片将在按钮化合物的顶部=底部->图片将在按钮的底部

语法如下:

photo = PhotoImage(file = "path_of_file")

文件路径是本地计算机上可用的任何有效路径。

代码1:

# importing only those functions
# which are needed
from tkinter import * 
from tkinter.ttk import *
  
# creating tkinter window
root = Tk()
  
# Adding widgets to the root window
Label(root, text = 'srcmini' , font = (
   'Verdana' , 15 )).pack(side = TOP, pady = 10 )
  
# Creating a photoimage object to use image
photo = PhotoImage( file = r "C:\Gfg\circle.png" )
  
# here, image option is used to
# set image on button
Button(root, text = 'Click Me !' , image = photo).pack(side = TOP)
  
mainloop()

输出如下:

Python |在Tkinter按钮上添加图像1

在输出中, 观察到按钮上仅显示图像, 并且按钮的尺寸也比通常的尺寸大, 这是因为我们尚未设置图像的尺寸。

代码2:

同时显示图片和文字

纽扣

.

# importing only those functions
# which are needed
from tkinter import * 
from tkinter.ttk import *
  
# creating tkinter window
root = Tk()
  
# Adding widgets to the root window
Label(root, text = 'srcmini' , font = (
   'Verdana' , 15 )).pack(side = TOP, pady = 10 )
  
# Creating a photoimage object to use image
photo = PhotoImage( file = r "C:\Gfg\circle.png" )
  
# Resizing image to fit on button
photoimage = photo.subsample( 3 , 3 )
  
# here, image option is used to
# set image on button
# compound option is used to align
# image on LEFT side of button
Button(root, text = 'Click Me !' , image = photoimage, compound = LEFT).pack(side = TOP)
  
mainloop()

输出如下:

Python |在Tkinter按钮上添加图像2

观察到文本和图像都出现了, 并且图像的尺寸也很小。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


赞(3)
未经允许不得转载:srcmini » Python在Tkinter按钮上添加图像

评论 抢沙发

评论前必须登录!