[英]How to control space between image and text on tkinter button widget?
我一直在为我为工作而编写的脚本开发一个 GUI,并且通过一些研究,我已经能够创建带有图像的按钮,以便于识别。 我唯一的问题是,现在图像和文本都固定在按钮的中间,这使得它笨拙,中间没有空格。
我想要做的是将图像对齐到按钮的左侧,将文本对齐到右侧。 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)
我想要做的是将图像对齐到按钮的左侧,将文本对齐到右侧。
Tkinter 无法将按钮左边缘的图像和右边缘的文本对齐。 但是,您可以通过简单地在文本中添加一两个空格并使用compound
选项将图像显式设置在文本左侧,将文本立即放在右侧并进行一些分隔。
bmi_btn = Button(top, compound="left", text=' Blastmaster Inputs', ...)
注意' Blastmaster Inputs'
中B
之前的空格
如果您希望图像位于按钮的最左侧,旁边有文本,请使用justify
选项:
button = tk.Button(..., justify="left")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.