gpt4 book ai didi

python - 如何控制 tkinter 按钮小部件上图像和文本之间的空间?

转载 作者:行者123 更新时间:2023-12-04 09:55:48 24 4
gpt4 key购买 nike

我一直在为我为工作编写的脚本开发 GUI,经过一些研究,我已经能够创建带有图像的按钮,以便于识别。我唯一的问题是,现在图像和文本都锚定在按钮的中间,这使得按钮之间没有空间变得笨拙。

enter image description here

我想要做的是将图像对齐到按钮的左侧,将文本对齐到右侧。有没有办法在 tkinter 中做到这一点?

这是我的用户界面代码:

def create_interface(self)->None:

ph_plan = ImageTk.PhotoImage(Image.open(self.plan_image))
ph_bmi = ImageTk.PhotoImage(Image.open(self.bm_image))
ph_calc = ImageTk.PhotoImage(Image.open(self.calc_image))
ph_plot = ImageTk.PhotoImage(Image.open(self.plot_image))

top = tk.Frame(self.root).grid(row=1)
middle = tk.Frame(self.root).grid(row=2, pady=40)
bottom = tk.Frame(self.root).grid(row=3, pady=80)


# Create buttons
bmi_btn = Button(top, text='Blastmaster Inputs', width=self.button_width,
image=ph_bmi, compound='left', bg='#f2fafc',
font=('Helvetica', 12, 'bold'), command=self.get_bm_inputs)
plan_btn = Button(top, text='Weekly Plan', bg='#f2fafc', font=('Helvetica', 12, 'bold'),
image=ph_plan, compound='left', width=self.button_width,
command=self.get_plan_output)
calc_btn = Button(bottom, text='Calculate sampling', height=80, width=self.button_width,
bg='#f2fafc', font=('Helvetica', 12, 'bold'), image=ph_calc,
compound='left', command=self.calculate_sampling)
self.plot_btn = Button(bottom, text='Create plots', height=80, width=self.button_width,
bg='#f2fafc', font=('Helvetica', 12, 'bold'), state='disabled',
image=ph_plot, compound='left', command=self.create_forecast_plots)

# Place buttons into window
bmi_btn.grid(row=1, column=1, pady=20)
plan_btn.grid(row=1, column=2, pady=20)
calc_btn.grid(row=4, column=1)
self.plot_btn.grid(row=4, column=2)

# Create references to image to protect from garbage collector
self.plot_btn.image = ph_plot
bmi_btn.image = ph_bmi
plan_btn.image = ph_plan
calc_btn.image = ph_calc

# Create labels
label_text1 = 'Enter start date for the forecast'
label_text2 = 'Enter end date for the forecast'
Label(middle, text=label_text1, font='Hevetica').grid(row=2, column=1)
Label(middle, text=label_text2, font='Helvetica').grid(row=3, column=1)

# Create and place data entry fields
self.start = Entry(middle, width=38)
self.start.grid(row=2, column=2)
self.end = Entry(middle, width=38)
self.end.grid(row=3, column=2)

最佳答案

What I would like to do is have images aligned to the left side of a button and text to the right side.

Tkinter 无法对齐按钮左边缘的图像和右边缘的文本。但是,您可以通过简单地向文本添加一两个空格并使用 compound 选项明确地将图像设置在文本的左侧,使文本紧靠右侧并有一些分隔。

bmi_btn = Button(top, compound="left", text=' Blastmaster Inputs', ...)

注意 ' Blastmaster Inputs' 中 B 之前的空格

如果您希望图像位于按钮的最左侧且旁边有文本,请使用justify 选项:

button = tk.Button(..., justify="left")

screenshot

关于python - 如何控制 tkinter 按钮小部件上图像和文本之间的空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61925165/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com