【发布时间】: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