在学习tkinter的过程中,我遇到了一个问题:我无法将图像添加到按钮中:
from tkinter import*
from tkinter import ttk
root=Tk()
button=ttk.Button(root)
button.grid()
photo=PhotoImage(file="giphy.gif")
button.config(image=photo, compound=RIGHT)
root.mainloop()
该代码出错:
<ipython-input-30-6ad3ebb78b5b> in <module>()
7 button.grid()
8 photo=PhotoImage(file="giphy.gif")
----> 9 button.config(image=photo, compound=RIGHT)
10
11 root.mainloop()
/usr/lib/python3.5/tkinter/__init__.py in configure(self, cnf, **kw)
1331 the allowed keyword arguments call the method keys.
1332 """
-> 1333 return self._configure('configure', cnf, kw)
1334 config = configure
1335 def cget(self, key):
/usr/lib/python3.5/tkinter/__init__.py in _configure(self, cmd, cnf, kw)
1322 if isinstance(cnf, str):
1323 return self._getconfigure1(_flatten((self._w, cmd, '-'+cnf)))
-> 1324 self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
1325 # These used to be defined in Widget:
1326 def configure(self, cnf=None, **kw):
TclError: image "pyimage.." doesn't exist
为什么会这样?我该如何解决?
答案 0 :(得分:1)
正如furas在评论中所说,您的代码可以通过interface TreeElem {
<T> T accept(TreeVisitor<T> visitor);
}
class Leaf implements TreeElem {
public <T> T accept(TreeVisitor<T> visitor) {
return visitor.visit(this);
}
}
class Split implements TreeElem {
private TreeElem left;
private TreeElem right;
Split(TreeElem left, TreeElem right) {
this.left = left;
this.right = right;
}
public <T> T accept(TreeVisitor<T> visitor) {
return visitor.combine(
visitor.visit(this),
left.accept(visitor),
right.accept(visitor));
}
}
interface TreeVisitor<T> {
T visit(Leaf tree);
T visit(Split tree);
T combine(T... inputs);
}
class Printer implements TreeVisitor<CharSequence> {
public CharSequence combine(CharSequence... inputs) {
StringBuilder text = new StringBuilder();
for (CharSequence input : inputs) {
text.append(input);
}
return text;
}
public CharSequence visit(Leaf tree) { return "leaf"; }
public CharSequence visit(Split tree) { return "split"; }
}
public class MWEjava {
public static void main(String[] args) {
TreeElem tree = new Split(new Leaf(), new Leaf());
Printer printer = new Printer();
System.out.println(tree.accept(printer));
}
}
完全运行。
错误来自您在Jupyter QtConsole中运行它的事实。
为了能够在Jupyter QtConsole中运行它,您需要明确告诉tkinter python script.py
的父窗口是什么。我认为这是因为在控制台中,默认父级不是您创建的PhotoImage
实例,而是一些隐藏窗口。因此,图像的父级不是按钮的父级,因此tkinter找不到图像。
以下代码应在控制台中运行:
Tk