我正在尝试向按钮添加图像,但是当我尝试执行当前代码时遇到了一些问题。它显示的只是一张没有文字的图像。我什至都看不到按钮。有什么办法可以修复我当前的代码?
from tkinter import *
import tkinter as tk
root = tk.Tk()
root.geometry("960x600")
canvas = Canvas(root, width=500, height=500)
canvas.pack()
imagetest = PhotoImage(file="giftest.gif")
canvas.create_image(250, 250, image=imagetest)
button_qwer = Button(root, text="asdfasdf", image=imagetest)
root.mainloop()
答案 0 :(得分:4)
您需要在窗口中pack
(或grid
)按钮,这是您可以执行的操作:
import tkinter as tk
from tkinter import PhotoImage
def print_hello():
print('hello')
root = tk.Tk()
root.geometry("960x600")
imagetest = PhotoImage(file="giftest.gif")
button_qwer = tk.Button(root, text="asdfasdf", image=imagetest, command=print_hello)
button_qwer.pack() # <-- don't forget to place the button in the window
root.mainloop()
您可以使用compound
选项在按钮上同时显示文字和图像,如下所示:
button_qwer = tk.Button(root, image=imagetest, text="asdfasdf", compound="top", command=print_hello)
compound
选项为bottom
,center
,left
,none
,right
或top
答案 1 :(得分:0)
您已成功制作了按钮,但未将其绘制到屏幕/界面上。使用pack
,place
或grid
。
button_qwer = Button(root, text="asdfasdf", image=imagetest)
button_qwer.pack()
您的完整代码如下:
from tkinter import *
import tkinter as tk
root = tk.Tk()
root.geometry("960x600")
canvas = Canvas(root, width=500, height=500)
canvas.pack()
imagetest = PhotoImage(file="giftest.gif")
canvas.create_image(250, 250, image=imagetest)
button_qwer = Button(root, text="asdfasdf", image=imagetest)
button_qwer.pack()
root.mainloop()