python - 当在 tk Button 中使用图像时,Button 消失

标签 python tkinter

这是我的代码,你可以忽略其中的大部分,但只能看到最后一部分有#

import tkinter as tk
from PIL import ImageTk, Image

def bresize_and_load(path):
    global bwidth, bheight
    im = Image.open(path)
    bwidth,bheight = im.size    
    resized = bresizemode(im, bwidth, bheight)    
    width,height = resized.size    
    return ImageTk.PhotoImage(resized)

def bresizemode(im, width, height):
    if height / width >= ratio:
        return im.resize((int(round((width / height) * usable_height)), usable_height), 
                  Image.ANTIALIAS)
       
    if height / width < ratio:
        return im.resize((usable_width, (int(round((height / width) * usable_width)))), 
                  Image.ANTIALIAS)

root = tk.Tk()
root.state("zoomed")
root.resizable(width=False, height=False)

frame = tk.Frame(root)

frame.grid(row = 0, column = 0, sticky = 'nsew')

tk.Grid.rowconfigure(root, 0, weight=1)
tk.Grid.columnconfigure(root, 0, weight=1)

row = 4
column = 5
for ro in range(row):
    tk.Grid.rowconfigure(frame, ro, weight=1)
for co in range(column):
    tk.Grid.columnconfigure(frame, co, weight=1)

root.update()
f_width  = frame.winfo_width()
f_height = frame.winfo_height()

booklistbutton = []
for i in range(row):
    for e in range(column):
        bbutton = tk.Button(frame, height = int(f_height / row), 
                            width = int(f_width / column))
        bbutton.grid(row = i, column = e)
        booklistbutton.append(bbutton)

root.update()
usable_width = booklistbutton[0].winfo_width()
usable_height = booklistbutton[0].winfo_height()
ratio = usable_height / usable_width

#here is image path
path = 'sample.jpg'
imm = []

#if it is range(20)(just = row * column) or less than column(here is 5), it work fine
for i in range(20):    
    imm.append(bresize_and_load(path))
    booklistbutton[i].config(image = imm[i])

root.mainloop()

我的问题是,如果您在按钮中加载图像,但图像按钮的数量不小于列或等于行*列,则图像按钮将消失。

当范围等于行*列(20)时:

http://i.imgur.com/XEjLH0n.png

当范围为6时:

http://i.imgur.com/kSO6MQw.png

这对我来说很奇怪,有人知道吗?

此外,如果不设置按钮的宽度和高度,它们也不会消失。但按钮会比图像大一点。

最佳答案

(代表 OP 发布解决方案)

我自己发现了问题,问题是当我设置按钮大小时,它是字符大小,但是当我加载图像时,它更改为像素大小,并且在相同大小的数字下,字符大小更大并且大于像素大小,因此图像按钮变得太小而无法显示。

关于python - 当在 tk Button 中使用图像时,Button 消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43058491/

相关文章:

python - Django 共享库/类

python - PIP 在 RaspberryPi 上安装 uamqp

python - 在 Python 中检查非常大的数字的素数

Python 使用 tkinter 在滚动文本框中搜索下一个单词

python - 以 pythonic 方式将所有列表元素更改为 true

python - Tkinter 的 .pack() 格式问题

python - 如何配置 MatPlotLib 工具栏,以便工具栏中的按钮是 ttk 按钮而不是旧的 Tk 按钮

python - cx_freeze错误: Module not found tkinter

python - 在 Tkinter 中如何不断获取 slider 值

python - 用python进行傅立叶变换