【问题标题】:Cannot create image button Python无法创建图像按钮Python
【发布时间】:2018-06-26 22:52:14
【问题描述】:

编辑: 我从这个视频中找到了一种方法: https://www.youtube.com/watch?v=8HwHqa3tq70

但对我来说它不起作用,这是我的代码:

from tkinter import *
from tkinter import ttk
rw = Tk()
b1 = ttk.Button(rw, text = "click")
b1.pack()

filepath = "2.jpg"
mi = PhotoImage(file = filepath)


b1.config(image = mi, compound = RIGHT)

我得到的错误是这里:

_tkinter.TclError: couldn't open "2.jpg": no such file or directory
>>> canv.create_image(20,20, anchor=NW, image=img)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'img' is not defined

对此有何建议?

【问题讨论】:

  • 我会为此推荐 Tkinter
  • 我在询问之前做了研究,但找不到任何适合我需要的教程。
  • 改变了问题
  • 试试2.jpg的绝对路径
  • @FrostFire 如果您还有其他问题,请创建另一个帖子,不要更改问题,阅读How to Ask

标签: python user-interface tkinter


【解决方案1】:

好的..你改变了问题。我把我的回答留给你上一个问题。我希望它有帮助。

您可以使用 PyQt5。 我有一个文件夹:

|-Project/
|--- images/
|----- 1.png
|------2.png
|--- app.py

有两个按钮,例如“cam”图标和“user”图标:

from PyQt5 import QtCore, QtGui, QtWidgets
import os

class Ui_Example(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(Ui_Example, self).__init__(parent)
        width = 350
        height = 180
        self.resize(width,height)
        self.setMaximumSize(width,height)
        self.setMinimumSize(width,height)
        self.setWindowTitle("Example")

        self.path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'images') #icons path

        ### icons

        usericon = QtGui.QIcon()
        usericon.addPixmap(QtGui.QPixmap(os.path.join(self.path, '2.png')), QtGui.QIcon.Normal, QtGui.QIcon.Off)

        camicon = QtGui.QIcon()
        camicon.addPixmap(QtGui.QPixmap(os.path.join(self.path, '1.png')), QtGui.QIcon.Normal, QtGui.QIcon.Off)

        # Button user
        self.btnuser = QtWidgets.QPushButton(self)
        self.btnuser.setGeometry(QtCore.QRect(20,20,150,100))
        self.btnuser.setIcon(usericon)
        self.btnuser.setStyleSheet("background-color:transparent;")
        self.btnuser.clicked.connect(self.ExecUserCode)
        # Button cam
        self.btncam = QtWidgets.QPushButton(self)
        self.btncam.setGeometry(QtCore.QRect(180, 20, 150, 100))
        self.btncam.setIcon(camicon)
        self.btncam.setStyleSheet("background-color:transparent;")
        self.btncam.clicked.connect(self.ExecCamCode)
        # Button..
        # ...

    def ExecUserCode(self):
        print("User Code here")
    def ExecCamCode(self):
        print("Cam Code here")

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MW = Ui_Example()
    MW.show()
    sys.exit(app.exec_())

结果是:

【讨论】:

  • 它工作得很好,而 tkinter 甚至在 Visual Studio Code 中也没有 pyqt5 工作。只是一个问题,我怎样才能使图像更大一点?并关闭 gui?
  • edit 我设法让图标变大,但我仍然不知道如何关闭 gui
  • 好吧,你可以使用 self.hide() 隐藏和执行某些东西,最后使用 self.show() 完成