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

от admin

Tkinter Button width

Tkinter Button width option sets width of the button in letters (for textual buttons) or pixels (for images). You can give only integer values for width option, be it number of lines or pixels.

In this tutorial, we will learn how to use width option to change the width of Tkinter Button.

Example 1 – Tkinter Button set Width

In the following program, we will change the width of Tkinter Button.

example.py – Python Program

Output

Conclusion

In this Python Tutorial, we learned about Tkinter Button width option and use it to change the width of a button, with the help of example Python programs.

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

Опции height и width виджета Tkinter Button задают размер создаваемой кнопки при инициализации. После инициализации все же можно было использовать метод configure для настройки опций height и width для программного изменения размера виджета Tkinter Button .

Please enable JavaScript

Укажите опции height и width для установки размера кнопки

height и width устанавливаются в единице текстовых единиц равными 20 . Горизонтальный текстовый блок равен ширине символа 0 , а вертикальный текстовый блок равен высоте 0 , оба в системном шрифте по умолчанию.

Полные рабочие коды

Как вы могли видеть, высота и ширина кнопки не совпадают в пикселях, хотя ее width и height установлены как 10 .

Установите width и height в пикселах кнопки Tkinter

Если нам нужно задать ширину и/или высоту виджета Tkinter Button в единице пикселей , то к Button можно добавить виртуальное невидимое изображение 1×1 пикселей. Тогда width и height будут измеряться в единицах пикселей .

Нам также нужно установить опцию compound в c или в равной степени tk.CENTER , если невидимое изображение и текст должны быть отцентрированы в кнопке. Если compound не настроен, то текст не будет отображаться в кнопке.

Измените размер кнопки после инициализации

После создания виджета Button метод configure может установить опции width и/или height для изменения размера Button .

Python Tkinter Button – How to use

In this Python tutorial, we will learn about Python tkinter button. Also we will see these topics.

  • Python Tkinter Button Command
  • Python Tkinter Button Styles
  • Python Tkinter Button Position
  • Python Tkinter Button size
  • Python Tkinter Button Color
  • Python Tkinter Button Shape
  • Python Tkinter Button Image
  • Python Tkinter Button Command Arguments
  • Python Tkinter Button Attributes
  • Python Tkinter Button Greyed Out

Table of Contents

Tkinter Button Command

  • The button widget is used to place a button on the screen.
  • Button holds a functionality that is triggered when pressed.

Syntax:

In this syntax, ws is the master, in place of the text you can mention the purpose of the button, Function or method should be passed as command.

.Code:

In this there is a subscribe button. When user clicks on that button, message box with thank you appears.

Output:

As you can see in the below output screen. A soon as the user clicked on the subscribe button he gets a prompt. If you want to call the function just once then add (), after calling the function. Like in this example command=subscribe()

Tkinter button Styles

  • Style is used to provide an improved look to buttons
  • It provides wide varieties of features like background, foreground, font, etc
  • A developer can prepare a template for designing a button
  • and using style it can be implemented on all the buttons
  • you can apply changes to a single button or multiple buttons

Code:

Output:

This output is implemented using style.

Tkinter Button Position

  • There are 3 layout managers: Pack, Grid, Place.
  • Pack is used to align widget in the center of the frame.
  • Grid uses row & column method of placing widgets.
  • Place is used to position widget in any coordinated provided as x & y

Syntax:

Code using pack:

Output:

In this output, pack is used to place the button. Pack aligns the widget in the center. That is why when screen is resized in second picture, the button remains in the center position.

Code using grid:

Output:

In this output, you can see that button is positioned at 0 row & 0 column that means top left side. In grid button remains in its position even if the window is resized.

Code using place:

Output:

In this output, buttons are positioned using the place. The place provides maximum control. AS you can see 2 buttons are placed in different positions, but since the screen size is smaller than the position of the second button is so it not appearing. But when the screen is stretched it starts appearing.

Tkinter Button size

  • Resizing of button simple means increasing or decreasing the width & height of the button widget.
  • This can be easily done using keywords width and height.

Code:

Output:

In this output, button size has been increased from a regular one. The standard size of button is mentioned in the above section. In this case height and width of the button has been increased.

Tkinter Button Color

  • Colour plays an important role in making the application look attractive & eye-catchy.
  • Buttons can also be painted in any colour.
  • there are 2 sections that need to be colored.
  • first is the background of the button second is the font color
  • bg keyword is used to paint the background
  • fg keyword is used to color the font.

Code:

Output:

In this output, background has been painted with blue and font colour is white. word & hexacode both are acceptable.

Tkinter Button Shape

  • Shape refers to applying shape in the button
  • Shapes can be rectangular, oval, circle, etc.
  • Shapes are not supported in tkinter
  • You cannot create a rounded button directly from the widget.
  • to do so you need a rounded image.
  • And then reduce the border width to 0.
  • To see the demo refer to Tkinter image section

Tkinter Button Image

  • Images improve the look of an application
  • to apply an image on a button we use image keyword

Code:

Output:

In this output, the Download button image is applied to the button widget. And it is clickable which means it is a button. But this has a button background. To remove the button border set borderwidth = 0. In the next image you can see there is no border in that.

Tkinter Button Command Arguments

  • Command button argument refers to providing input in the command button
  • In a calculator, the code takes a key argument through a button command.
  • Similarly, we will write code that will send a number to the function

Code:

Output:

So in this output, argument in the form of key name ie. 1 or 2 or 3 is passed to the function wherein these numbers are printed in the entry box.

Tkinter Button Attributes

  • Attributes are the properties of button widget
  • It holds list of all the features of widget
  1. activebackground & activeforeground
  • active background changes background colour of the button when clicked
  • activeforeground changes text color when button is clicked
Читать:
Ntfsck 00000000 что это

Code:

Output:

In this output, the first image shows the button without click but the second image shows the change in background colour & text colour when clicked. It will become normal as soon as the button will be released

2. colours:

  • colours plays an important role in software development.
  • Every colours has some meaning like red for error, green of correct, etc.
  • bg is used to fill background colour of the label
  • fg is used to change the text colour.
  • you can either provide a colour name or hex code

Example:

3. font :

  • fonts make text readable.
  • to know more about fonts.

Example:

4. relief:

  • relief is used to provide decoration to the border.
  • It has various options that can be used to emphasize text.
  • Button border defines the type of border & its thickness.
  • There 6 types of borders each having their on property:
    • Flat
    • Raised
    • Sunken
    • ridge
    • solid
    • groove

    Syntax: borderwidth should be provided any integer value, relief should provide anyone out of these ( flat, raised, sunken, ridge, solid, groove).

    Code:

    Output:

    In this output, all types of border are displayed, each have width of 3 pixels. padx & pady determines the extra space around the box.

    Example:

    5. Height & Width:

    • Height determines the vertical dimension of the Button.
    • Width determines the horizontal dimension of the Button.

    Example:

    6. padx & pady

    • padx adds empty space vertically
    • pady adds empty space horizontally
    • if they are used within the Button then they add extra space inside the box
    • if they are used in the positioning section (pack/grid/place) then add space outside the box.

    Example: Inside the box

    7. Justify:

    • Justify is used for alignment.
    • It works similar to anchor but has only three options
    • LEFT, CENTER, RIGHT

    Example:

    Python Tkinter Greyed Out Button

    • Python Tkinter button Greyed out means button is in disable state & it can’t be clicked.
    • This method is used when a developer doesn’t want the user to proceed without fulfilling the requirement.
    • Next time if you see accept terms and conditions option somewhere on a website or software try going through accepting it. You will notice that button is disabled & it is not clickable.
    • state method is used to switch between NORMAL or DISABLED state.
      • NORMAL: Button is clickable and is ready to trigger a function
      • DISABLED: Button is greyed out and can’t be clicked.

      Syntax:

      Code:

      In this code, we have created a demonstration of button greyed out. There is a button that is in disabled state. When user will check on the checkbox then this button will turn into normal state.

      Output:

      In this output, you can see that in the first picture the button is greyed out or is disabled but as soon as user accepted the terms and conditions but is normal and clickable.

      You may like the following Python tutorials:

      In this tutorial we have learned Python Tkinter Button:

      • Python Tkinter Button Command
      • Python Tkinter Button Styles
      • Python Tkinter Button Position
      • Python Tkinter Button size
      • Python Tkinter Button Color
      • Python Tkinter Button Shape
      • Python Tkinter Button Image
      • Python Tkinter Button Command Arguments
      • Python Tkinter Button Attributes
      • Python Tkinter Button Greyed Out

      Bijay Kumar MVP

      Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

      How do I resize buttons in pixels? (Tkinter)

      I am making a Tic Tac Toe game in Python Tkinter but the buttons are rectangles, and I want them to all be 100×100 pixels in size. I tried using:

      (ignore the empty string and a1 ) and yet it does not resize it into a square. I have written most of the code and don’t want to use frames to resize them. What should I do?

      eyllanesc's user avatar

      5 Answers 5

      One simple method is to give the button an invisible 1×1 pixel image. When you do that, the width and height attributes are interpreted as pixels (or more accurately, screen units, which could also mean points, inches, or centimeters).

      If you do this, you can set compound to the value «c» to mean that the button should show both text and the image, with both being centered on the window.

      If you are adding the button with the place method, you can use the expression:

      With this, the button is created with a size of 200×30 px within its parent object at the position x = 0, y = 0

      Das_Geek's user avatar

      The way I would want to make sure a button is a specific size in pixels is by placing that button inside of a frame and making sure the frame is set to a specific size and the button is set to fill that frame.

      This can easily be converted to work in your program and it makes sure the buttons are set to exactly 100 x 100.

      This is the only way I am aware of to be sure of the size of a button in pixels. There may be other options.

      First we will need 2 list. One to hold the frames and one to hold the buttons. This will allow us to store the frames and buttons in an easy way that we can work with later.

      I am not sure off the top of my head on how to condense your check_win() function so I will only make a minor change to it so it will work with the lists. We need to replace each instance of a1 , a2 , a3 , and so on with its counterpart in the buttons list with the index value that is going to be created with the for loop later.

      Then we need to change the process_turn() function to include the index value of each button in the buttons list so add an argument to it like this.

      Finally we need to create all the buttons with the correct index in the command and we can do this with a for loop. Well 2 for loops.

      The first loop will start the row count and the 2nd for loop will work the column count. This creates our 3 by 3 grid. The ndex variable is used to keep track of the index that each button needs to configure on the buttons list.

      All put together you have this code that has the exact 100×100 pixel sizing you wanted.

Похожие статьи