如何在按钮中垂直居中显示文本?

时间:2017-12-15 15:00:39

标签: python button text tkinter

我在一个框架内有一个按钮:

self.b = tk.Button(self.subframe1, text="UPDATE", command = self.update)

此按钮中的文本将水平居中,但不会垂直居中。可以做后者吗?

1 个答案:

答案 0 :(得分:0)

正如@gandreadis评论的那样,您可以依靠anchor选项来完成这项工作。

这是一个MCVE(在Python 3.x中):

import tkinter as tk


class Test:

   def __init__(self, master):
       self.master = master
       self.configure_gui()
       self.create_widgets()
       self.configure_widgets()

   def configure_gui(self):
       self.master.title("Button Text Centering")
       self.master.geometry('300x100')
       self.master.resizable(0, 0)

   def create_widgets(self):
       self.create_demo_button()

   def create_demo_button(self):
       self.btn_with_centered_text = tk.Button(self.master, text="Centered")
       self.btn_with_centered_text.place(relx=0.5, rely=0.5, anchor=tk.CENTER)
       self.btn_with_centered_text.config(bg="yellow")

   def configure_widgets(self):
       self.configure_btn_with_centered_text()

   def configure_btn_with_centered_text(self):
       self.btn_with_centered_text.config(bg="yellow", relief=tk.RAISED)
       self.btn_with_centered_text.config(border="2px")


def main():
   root = tk.Tk()
   t = Test(root)
   root.mainloop()

if __name__ == '__main__':
   main()   

演示:

enter image description here