簡體   English   中英

在 tk Button 中使用圖像時,Button 消失

[英]When use image in tk Button, Button disappear

這是我的代碼,您可以忽略其中的大部分,但只能看到具有 # 的最后一部分

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發布解決方案)

我自己發現了這個問題,問題是當我設置Buttons的大小時,它是chr大小,但是當我加載圖像時,它變為像素大小,並且在相同的大小數字下,chr大小越來越大像素大小,因此圖像按鈕變得太小而無法顯示。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM