我正在尝试使用python tkinter将图像制作成按钮。但是,图像按钮仅在我将一个字符放在下面一行时显示

2024-05-14 01:25:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个按钮图像。打开弹出窗口时,我希望图像按钮位于特定位置(我使用了网格方法)。但是,只有在按钮代码下方的行中包含字符(任何字符)时,按钮才会出现。 当包含字符时,将显示图像,按下该图像调用的功能将完美工作。不过,当弹出窗口最初出现时,我确实收到一条错误消息

这是我的密码:

def eastereggtxt1():
    function works fine so don't worry about this 
    function

img = PhotoImage(file = r'pathtoimage.png')

imgbutn = Button(EntryWindow,
image = img, borderwidth = 0,
command = eastereggtxt1)
imgbutn.grid(row = 18, column = 7)

r

图像/按钮仅在我使用上面的字符“r”运行时显示。然而,字符实际上可以是任何字母。没有它,图像就不会显示

知道为什么会这样吗


Tags: 方法代码图像功能网格消息密码img
2条回答

您可以使用标签而不是按钮。这可能是一个不错的选择。 但您需要更改几行代码

eastereggtext1()函数中,传递参数event。 例如:

def eastereggtext(event):
    # function code here...

然后,移除按钮并添加图像

imgbutn = Label(root, image=img)
imgbutn.grid(row = 18, column = 7)

然后,将标签绑定到鼠标单击

imgbutn.bind("<Button-1>", eastereggtext1)

有关tkinter绑定的详细信息:Python | Binding function in Tkinter

下面是完整的代码:

from tkinter import Tk, Button, PhotoImage
# other modules you need to import

root = Tk()
root.title("Title of the window")

def eastereggtext1(event):
    # function code here....

img = PhotoImage(file = 'image_path.png')

imgbutn = Label(root, image=img)
imgbutn.grid(row = 18, column = 7)
imgbutn.bind("<Button-1>", eastereggtext1)

root.mainloop()

假设您的代码如下所示:

from tkinter import *
from tkinter.ttk import *

root = Tk()

def eastereggtxt1():
    print("Easter Eggs!")

image = PhotoImage(file = r'easter_eggs.png') # I use easter_eggs as an example

image_button = Button(root, image = image, command = eastereggtxt1)
image_button.grid(row = 18, column = 7)
mainloop() # I just know that you can just do mainloop(), but it's not effective

我尝试了代码,它工作正常,但是当我尝试用其他东西替换r(例如:l,p,s)时,出现了一个错误:

PS C:\Users\user#1> python -u "D:\Test\test1.py"
  File "D:\Test\test1.py", line 9
    img = PhotoImage(file = s'easter_eggs')
                             ^
SyntaxError: invalid syntax

它表示代码不能使用除r以外的任何其他字符

你还提到:

The image/button only shows up if I run it with the above character "r" included.

我认为你的操作系统不支持没有字符r?如果这是错误的,请在评论中告诉我

和平:D

相关问题 更多 >