繁体   English   中英

图像未应用到 Tkinter 中的按钮上

[英]Images not getting applied on the button in Tkinter

以下项目应该在单击某个彩色按钮时显示一条消息。 但是,每当我执行程序时,它会在正确的 alignment 等中显示空白(白色)按钮。由于某种原因,图像未加载。 将来,我计划添加不同的图像,因此使用在 Paint 中创建的彩色图像进行测试,而不是使用内置命令来显示颜色。 我将在代码之后添加下面的结果。

编辑:所有图像都是在 Microsoft Paint 中创建的 100x100 像素。我尝试过其他模块,如 PIL,但无济于事。

# importing the module
import tkinter
import tkinter.messagebox
from tkinter import *
# importing the module

# initialising tkinter
class window(Frame):

    def __init__(self,master = None):
        Frame.__init__(self,master)
        self.master = master
# initialising tkinter

# creating the window
root = Tk()
app = window(root)
root.geometry("350x350")
# creating the window

# colours
WHITE = (255,255,255)
BLACK = (0,0,0)
BLUE  = (0,0,255)
RED   = (255,0,0)
# colours

# image


red_image = "red.png"
blue_image = "blue.png"
yellow_image = "yellow.png"
green_image = "green.png"

# image

# creating a button function
def create_button(x,y,color,color2,picture):
    click = Button(root, image = PhotoImage(picture), width= 150, height=150, command = lambda : tkinter.messagebox.showinfo( "Hello Python", "This is " + color))
    click.image = PhotoImage(picture)
    click.grid( row = x, column = y)
# creating a button function

create_button(0,0,'red','pink',red_image)
create_button(0,2,'blue','lightblue',blue_image)
create_button(2,0,'green','lightgreen',green_image)
create_button(2,2,'yellow','lightyellow',yellow_image)

# starting the widget
root.mainloop()
# starting the widget

目录

结果

您的代码中有两个问题:

  • 您将文件名传递给PhotoImage()而不使用file关键字: PhotoImage(picture)应该是PhotoImage(file=picture)

  • 您没有保留分配给按钮的图像的引用,而是另一个图像实例

以下是修复了问题的更新create_button() function:

def create_button(x, y, color, color2, picture):
    image = PhotoImage(file=picture)
    click = Button(root, image=image, width=150, height=150, command=lambda: tkinter.messagebox.showinfo("Hello Python", "This is "+color))
    click.image = image
    click.grid(row=x, column=y)

要在Button中添加图像,您没有使用适当的关键字。

这是一个简单的示例,您可以在按钮中添加图像

from tkinter import * 
from tkinter.ttk import *
# creating tkinter window 
root = Tk() 
# Adding widgets to the root window 
Label(root, text = 'Image adding', font =( 'Verdana',15)).pack(side = TOP, pady = 10) 

  # Creating a photoimage object to use image 

photo = PhotoImage(file = "C:\Gfg\circle.png") 
# here, image option is used to 
# set image on button 

Button(root, text = 'Click Me !', image = photo).pack(side = TOP) 
root.mainloop() 

我想它可以帮助你

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM