Как изменить размер кнопки в tkinter
Перейти к содержимому

Как изменить размер кнопки в tkinter

  • автор:

Размер кнопки Button

добрый день. понимаю что нубский вопрос=)но всё же. накидываю gui приложения через tkinter и столкнулся с такой проблемой.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
from tkinter import * root = Tk() root.title('Search Engine') root.geometry('300x300') root.resizable(False, False) Label(text='Word search:').grid(row=0, column=0, columnspan=2) word_input = Entry(width=36) word_input.grid(row=0, column=2) Label(text='File:').grid(row=1, column=0) Button(text=". ", width=5).grid(row=1, column=1) #Кнопка file_input = Entry(width=36) file_input.grid(row=1, column=2) root.mainloop()

как по высоте сделать кнопку в приложении меньше?
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
Ответы с готовыми решениями:

Как добавить кнопки (if (GUI.Button(new Rect(x1, y1, dx, dy), ii.name) в список List?
Хочу все кнопки добавить в список и выводить на экран из списка. void OnGUI() < if.

Как сделать, чтобы при нажатии кнопки Push Button загоралась та или иная кнопка Radio Button
вопрос: Как сделать,чтобы при нажатие кнопки Push Botton загоралась та или иная кнопка Radio Button?

Изменить цвет кнопки (button) по нажатию кнопки
Здравствуйте, подскажите, пожалуйста, как сделать что когда нажимаешь на копку меняется цвет.

1287 / 672 / 365
Регистрация: 07.01.2019
Сообщений: 2,201

ЦитатаСообщение от Typh0on Посмотреть сообщение

как по высоте сделать кнопку в приложении меньше?
Попробуйте параметр height у Button
Регистрация: 29.03.2020
Сообщений: 9

в общем нагуглил что решить проблему можно если Button присвоить картинку. Просто у Button единица измерения изначально это символ на сколько я понял и при присвоении картинки единица измерения меняется на пиксели. Получилось. не знаю на сколько правильно так пользоваться этим виджетом, других решений не нашёл.

pixel = PhotoImage(width=1, height=1) Button(text=". ", image=pixel, width=30, height=10, compound="c")

Регистрация: 02.02.2020
Сообщений: 5

btn1 = Button(root, text = 'Сохранить', command = speed) btn1.place(x = 220, y = 10, width = 70, height=10)

87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
Помогаю со студенческими работами здесь

Привязать размер контента к размеру Button
Здравствуйте. Как привязать размер текста(content) к размеру кнопки, чтобы при изменении размера.

Изменился размер кнопки «свернуть все окна». Как вернуть прежний размер?
Такая проблема уже была на RC версии ОС, думал на финалке этого не произойдет, ан нет) произошло.

Button кнопки
Ребят кто может помочь сделать вот такую панель с помощью тега button?

Отображение кнопки button
Доброе время суток. Друзья , проблема следующая: добавил кнопку через картинку, и сверху над.

Вращение кнопки (Button)
Привет всем! Народ подскажите можно ли в VB.net замутить вращение стандартной кнопки (Button) и.

Отображение кнопки button
Доброе время суток. Друзья , проблема следующая: добавил кнопку через картинку, и сверху над.

Не меняется размер размер кнопок в Tkinter

Причём до этого у меня был другой шрифт в кнопках и размер кнопок менялся в зависимости от размера шрифта но после удаления шрифта размер не меняется. До удаления шрифта код выглядел так:

helv36 = tkFont.Font(family='Helvetica', size=10) save = tk.Button(root, text='Save', relief="flat", bg='#8DFF61', font=helv36) save.pack(side='left', pady=40, anchor='s', expand=1) save.config(width=10, height=50, command=save_p) exit = tk.Button(root, text='Close', relief="flat", bg='#B0B0B0', font=helv36) exit.pack(side='right', pady=40, anchor='s', expand=1) exit.config(width=10, height=50, command=close) 

Менять размер кнопок в конфиге уже пробовал

Python-сообщество

[RSS Feed]

  • Начало
  • » GUI
  • » Как изменить размер шрифта кнопки, не изменяя ее размер (TKinter)?

#1 Авг. 24, 2015 23:40:58

Peri-Reis Зарегистрирован: 2015-08-24 Сообщения: 4 Репутация: 0 Профиль Отправить e-mail

Как изменить размер шрифта кнопки, не изменяя ее размер (TKinter)?

from Tkinter import * root = Tk() root.geometry('500x500') btn = Button(root, width='25', height='10', font='Arial 20') btn.pack() root.mainloop() 

Размер кнопки изменяется в зависимости от размера шрифта, не смотря на заданные width и height. Как этого избежать?

#2 Авг. 24, 2015 23:49:12

4kpt_III Зарегистрирован: 2014-12-22 Сообщения: 999 Репутация: 39 Профиль Отправить e-mail

Как изменить размер шрифта кнопки, не изменяя ее размер (TKinter)?

width и height в кнопке не задается в пикселях. Он задается в символах. Т.е. длина 25 символов. С увеличением размера шрифта увеличивается и размер символов, соответственно увеличивается и размер кнопки.

Change the Tkinter Button Size

Change the Tkinter Button Size

  1. Specify height and width Options to Set Button Size
  2. Set width and height in Pixels of Tkinter Button
  3. Change Tkinter Button Size After Initialization

height and width options of Tkinter Button widget specify the size of the created button during the initialization. After initialization, we could still use the configure method to configure the height and width option to change the size of the Tkinter Button widget programmatically.

Specify height and width Options to Set Button Size

tk.Button(self, text="", height=20, width=20) 

The height and width are set to be 20 in the unit of text units. The horizontal text unit is equal to the width of the character 0 , and the vertical text unit is equal to the height of 0 , both in the default system font.

The reason why Tkinter uses text units for measurement of width and height but not inches or pixels is that text unit ensures the consistent behavior of Tkinter across different platforms.

Complete Working Codes

import tkinter as tk import tkinter.font as tkFont  app = tk.Tk() app.geometry("400x200")  buttonExample1 = tk.Button(app, text="Button 1", width=10, height=10) buttonExample2 = tk.Button(app, text="Button 2", width=10, height=10)  buttonExample1.pack(side=tk.LEFT) buttonExample2.pack(side=tk.RIGHT)  app.mainloop() 

Tkinter Button_set height and width size

As you could see, the height and width of the button are not the same in the pixels although its width and height are set to be both 10 .

Set width and height in Pixels of Tkinter Button

If we need to specify the width and/or height of Tkinter Button widget in the unit of pixels , we could add a virtual invisible 1×1 pixel image to the Button . Then the width and height will be measured in the unit of pixel .

tk.Button(app, text="Button 1", image=pixelVirtual, width=100, height=100, compound="c") 

We also need to set the compound option to be c or equally tk.CENTER if the invisible image and text should be centered in the button. If compound is not configured, the text will not show in the button.

import tkinter as tk import tkinter.font as tkFont  app = tk.Tk() app.geometry("300x100") fontStyle = tkFont.Font(family="Lucida Grande", size=20)  labelExample = tk.Label(app, text="20", font=fontStyle)  pixelVirtual = tk.PhotoImage(width=1, height=1)  buttonExample1 = tk.Button(  app, text="Increase", image=pixelVirtual, width=100, height=100, compound="c" ) buttonExample2 = tk.Button(  app, text="Decrease", image=pixelVirtual, width=100, height=100, compound="c" )  buttonExample1.pack(side=tk.LEFT) buttonExample2.pack(side=tk.RIGHT) app.mainloop() 

Change Tkinter Button Size After Initialization

After the Button widget has been created, the configure method could set the width and/or height options to change the Button size.

buttonExample1.configure(height=100, width=100) 

It sets the height and width of buttonExample1 to be 100 .

Complete Working Examples to Change Button Size After Initialization

import tkinter as tk import tkinter.font as tkFont  app = tk.Tk() app.geometry("600x500")  def decreaseSize():  buttonExample1.configure(height=100, width=100)  def increaseSize():  buttonExample2.configure(height=400, width=400)  pixelVirtual = tk.PhotoImage(width=1, height=1)  buttonExample1 = tk.Button(  app,  text="Decrease Size",  image=pixelVirtual,  width=200,  height=200,  compound="c",  command=decreaseSize, ) buttonExample2 = tk.Button(  app,  text="Increase Size",  image=pixelVirtual,  width=200,  height=200,  compound=tk.CENTER,  command=increaseSize, )  buttonExample1.pack(side=tk.LEFT) buttonExample2.pack(side=tk.RIGHT) app.mainloop() 

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

Related Article — Tkinter Button

  • Pass Arguments to Tkinter Button Command
  • Close a Tkinter Window With a Button
  • Change Tkinter Button State
  • Bind Multiple Commands to Tkinter Button
  • Create a New Window by Clicking a Button in Tkinter

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *