【问题标题】:How to get all the buttons to be automatically the same size depending on the largest one in tkinter using canvas?如何根据 tkinter 中使用画布的最大按钮自动使所有按钮大小相同?
【发布时间】:2021-05-15 00:35:17
【问题描述】:

无论您在其中插入的文本如何,您应该如何将所有按钮的大小设置为相同的大小,它们都应该根据最大的那个来调整大小。 已经有一个类似我的问题的答案,但它是使用grid 完成的,我正在使用画布在窗口中放置背景图像并放置按钮。

根据文本自动将按钮设置为相同大小是否值得麻烦,因为我的文本将始终保持相同...

我尝试使用 cget() 获取按钮的大小,但返回 0。它在哪里存储其宽度,因为它必须以某种方式调整自身大小,即使它是根据文本进行的?可以以任何方式访问它吗?我本来想用这个值来调整其他按钮的值,但结果失败了。

如果你想知道我为什么要把它变成一门课,我也想试试。

我通过将所有按钮放在一个框架中并将它们告诉fill=x 使其工作,但是使用框架破坏了使用画布的意义,因为由于框架覆盖了背景而无法看到背景。有没有办法让画布中的框架透明,这也可能解决我的问题。

from tkinter import *

class ThreeButtonMenu():
    def __init__(self, button1_text, button2_text, button3_text, image_height = 600, image_width = 500, bg_input = 'space_background.png'):

        self.root = Tk()

        HxW = str(image_height)+'x'+str(image_width)
        self.root.geometry(HxW)
        self.root.maxsize(image_height,image_width)
        self.root.minsize(image_height,image_width)

        self.root.title('Guess')

        bg = PhotoImage(file=bg_input)

        background_canvas = Canvas(self.root, width = 600, height=500)
        background_canvas.pack(fill="both", expand=True)

        background_canvas.create_image(0,0, image=bg, anchor='nw')

        

        button1 = Button(self.root, text=button1_text, font = ('Lato',28))
        button2 = Button(self.root, text=button2_text, font = ('Lato',28))
        button3 = Button(self.root, text=button3_text, font = ('Lato',28), command = self.root.destroy)

        button1_window = background_canvas.create_window(300,45, anchor=N, window=button1)
        button2_window = background_canvas.create_window(300,160, anchor=N, window=button2)
        button3_window = background_canvas.create_window(300,275, anchor=N, window=button3)


        print(button1.cget('width'))
        print(button2.cget('width'))
        print(button3.cget('width'))
           
        self.root.mainloop()


start_menu = ThreeButtonMenu('Start Game', 'Leaderboard', 'Quit')

感谢您的回答。

【问题讨论】:

    标签: python python-3.x tkinter button


    【解决方案1】:

    当您使用几何管理器(packplacegrid)时,通常会这样做。

    例如,您需要在每个按钮上调用pack。请参阅下面的pack 示例。

        import tkinter as tk
        
        root = tk.Tk()
        for text in (
                "Hello", "short", "All the buttons are not the same size",
                "Options", "Test2", "ABC", "This button is so much larger"):
            button = tk.Button(root, text=text)
            button.pack(side="top", fill="x")
        
        root.mainloop()
    

    【讨论】:

    • 我已经阅读了,但是你可以将它用于画布窗口吗?我不确定如何诚实地在我的代码中实现它。我只是拿 button_windows 并把 .pack() 放在上面吗?
    • 您需要单独打包每个按钮。
    • 我已经做到了,谢谢。我应该删除这个问题,因为它基本上是重复的。感谢您为我解决问题!
    • 我已经更新了答案,最好留在此处而不是删除,因为将来有人可能会遇到与您相同的问题。
    猜你喜欢
    • 2018-05-31
    • 2015-11-15
    • 1970-01-01
    • 2019-07-28
    • 2014-03-07
    • 2011-09-09
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多