Home > Mobile >  Why does the text on my button not appear?
Why does the text on my button not appear?

Time:01-27

I'm making a text editor and I'm adding a navbar but the text on FileBtn doesn't appear.

from tkinter import *

##############################################

# Constants
width = 800
height = 450

##############################################

# Window Creation
Window = Tk()
Window.geometry(F'{width}x{height}')
Window.title("TextWrite")

##############################################

# Navbar Creation
Navbar = Frame(Window, width = width, height = 25, bg = "#141414")
Navbar.place(x = 0, y = 0)

# File Options Creation

def OpenFileOptions():
    FileOptions.place(x = 0, y = 25)

FileBtn = Button(Window, width = 10, height = 25, text = "File", bg = "#171717", fg = "white", command = OpenFileOptions)
FileBtn.place(x = 0, y = 0)

FileOptions = Frame(Window, width = 10, height = 50)
FileOptions.place(x = -1000, y = 0)

##############################################

# Text Input Creation
Input = Text(Window, width = width, height = 425, bg = "#202020", fg = "white")
Input.place(x = 0, y = 25)

Window.mainloop()

I searched for my problem but nothing I found seemed to fix it. This is the first time I have encountered this error, and I have no clue why it happens.

CodePudding user response:

The main problem is that you've set the height of the button to 25 lines tall. The width and height for some widgets -- including buttons -- is in number of characters, not pixels. Tkinter will center the text in the widget, so the text was very far down and out of view.

You can actually see this if you remove the text widget. You'll see that the button is very tall and the button label is centered in the button but roughly in the middle of the widget. (note: the following screenshot was taken on a Mac, which doesn't support changing the background color of buttons)

screenshot without the text widget

If you remove the height attribute altogether or set height to 1, you'll see the text, though you might have to also change the colors.


If you're just now learning tkinter, I strongly encourage you to use pack and/or grid rather than place. There's a slight learning curve, but it's much easier to make GUIs that are responsive and that make optimal use of the window size. place is best for very unique circumstances rather than as a general purpose tool.

CodePudding user response:

but the text on FileBtn doesn't appear

No need to change value. In line 37, change this y=25 to y=400. Should be like this: Input.place(x = 0, y = 400)

Screenshot:

enter image description here

  • Related