按钮图像没有出现在tkinter中

时间:2015-03-31 03:00:59

标签: python tkinter yosemite

我是tkinter的新手,我正在使用Yosemite下的IDLE 3.4.2运行Tk版本8.5.17的python 3.4.2。这是Liang的书使用Python 3编程简介的修改演示。我期待以下代码显示四个按钮:

from tkinter import *

class ButtonsDemo:
    def __init__(self):
        window = Tk()
        window.title("Buttons Demo")

        frame0 = Frame(window)  
        frame0.pack()

        plusImage = PhotoImage(file = "image/plus.gif")
        minusImage = PhotoImage(file = "image/minus.gif")
        timesImage = PhotoImage(file = "image/times.gif")
        divideImage = PhotoImage(file = "image/divide.gif")

        Button(frame0, image = plusImage, command =
                 self.add).grid(row = 1, column = 1, sticky = W)
        Button(frame0, image = minusImage, command =
                 self.subtract).grid(row = 1, column =2)
        Button(frame0, image = timesImage, command =
                 self.multiply).grid(row = 1, column = 3)
        Button(frame0, image = divideImage, command =
                 self.divide).grid(row = 1, column = 4)
        window.mainloop()

    def add(self):
         print("add pressed")

    def subtract(self):
         print("subtract pressed")

    def multiply(self):
         print("multiply pressed")

    def divide(self):
         print("divide pressed")

ButtonsDemo()

运行代码时,只显示前三个按钮。不显示带有divideImage的按钮。

如果我点击分割按钮的位置,我会收到消息“分开按下”。好像按钮在那里,但它是不可见的。

我看到从命令行运行程序的行为相同 而不是来自IDLE。

gif没什么问题。如果我使用divide.gif作为plusImage,我可以在第一个按钮位置看到divide.gif。此外,当我将text = "Divide"放在除法按钮上而不是image = DivideImage时,该按钮变为可见。

为什么使用图像时分割按钮不可见?我该如何解决?

编辑:这是将所有内容移动到主程序的代码。我认为这应该修复了垃圾收集问题,如果有的话。它是否正确?

from tkinter import *

def add():
         print("add pressed")

def subtract():
     print("subtract pressed")

def multiply():
     print("multiply pressed")

def divide():
     print("divide pressed")


window = Tk()
window.title("Buttons Demo")
frame0 = Frame(window)  
frame0.pack()

plusImage = PhotoImage(file = "image/plus.gif")
minusImage = PhotoImage(file = "image/minus.gif")
timesImage = PhotoImage(file = "image/times.gif")
divideImage = PhotoImage(file = "image/divide.gif")

Button(frame0, image = plusImage, command =
             add).grid(row = 0, column = 0, sticky = W)
Button(frame0, image = minusImage, command =
             subtract).grid(row = 0, column = 1)
Button(frame0, image = timesImage, command =
             multiply).grid(row = 0, column = 2)

Button(frame0, image = divideImage, command =
             divide).grid(row = 0, column = 3)

window.mainloop()

0 个答案:

没有答案