customtkinter - align text in CTkLabel - python

I want my text to be aligned to the left (or west).
My code:
import customtkinter as ctk
import tkinter as tk
root = tk.Tk()
root.geometry("300x100")
label = ctk.CTkLabel(master=root,
text="this is a label",
text_color="#fff",
bg_color="green",
width=250,
justify="left",
anchor="w"
)
label.place(x=0, y=0)
root.mainloop()
Even with justify="left" and anchor="w" nothing changes and the text is centered. Why? And how can I fix it?

Actually CTKLabel is a Frame and the text is a Label inside that frame. The text is put at center of the frame using place(relx=0.5, rely=0.5, anchor='c'). So the justify and anchor options passed to CTKLabel does not work.
However, you can move the text after creating the instance as below:
label = ctk.CTkLabel(master=root,
text="this is a label",
text_color="#fff",
bg_color="green",
width=250,
justify="left",
anchor="w"
)
label.text_label.place(relx=0, anchor='w') # move the text to the left side of frame
label.place(x=0, y=0)
Or making the text to fill the frame horizontally:
label.text_label.place(relwidth=1)

This could be solve your problem: anchor=ctk.W
And here is the code:
label = ctk.CTkLabel(master=root,
text="this is a label",
text_color="#fff",
bg_color="green",
anchor=ctk.W)

Adding justify worked for me. I was able to center align the text inside the Custom TKinter textbox (CTKEntry)
example:
testEntry = customtkinter.CTkEntry(master=f1,
justify=CENTER,
width=120,
height=120,
corner_radius=2)
Regards,
V.M.Guruprasath

Related

Buttons not being placed inside the correct frame in tkinter

I am a newbie trying to use tkinter to build a GUI for an application. So far, I have a frame that I'd like to put several buttons into. However, every time I attempt to position this button, it isn't placed properly, being put outside of the frame itself. I wouldn't like to use the place function because of the several buttons I have to dynamically generate coming from an excel sheet so I was hoping to use the grid function instead.
Here is what I have so far
from tkinter import *
from customtkinter import *
window = Tk()
window.geometry("1920x1080")
window.state("zoomed")
window.title("My Company's Description Printer")
main_frame = CTkFrame(window, width=1920, height=1080, fg_color="grey21")
main_frame.place(x=0, y=0)
title = Label(main_frame,
text="My Company",
bg="grey21",
fg="white",
font=("Trajan Pro", 20)).place(x=626, y=30)
button_frame = CTkCanvas(main_frame,
width=800,
height=600,
highlightthickness=3,
highlightbackground="black",
relief="ridge",
bg="grey19").place(x=60, y=110)
test_button = CTkButton(button_frame, text="test").grid(row=0, column=0)
window.mainloop()
Example of code being ran
As you can see, the button is being placed in the top left corner of the entire window rather than the top left corner of the black bordered button frame. Any help would be appreciated. Thank you so much.
Note that button_frame is None because it is the result of .place(...), so the button (test_button is None as well due to same reason) is a child of the root window instead of the instance of CTkCanvas. .place(...) should be called in separate line.
Also .create_window() is used instead of tkinter layout manager to put widget into a canvas:
...
button_frame = CTkCanvas(main_frame,
width=800,
height=600,
highlightthickness=3,
highlightbackground="black",
relief="ridge",
bg="grey19")
# call .place(...) in separate line
button_frame.place(x=60, y=110)
test_button = CTkButton(button_frame, text="test") # don't use .grid(row=0, column=0)
# use .create_window() to put widget into canvas
button_frame.create_window(0, 0, window=test_button, anchor="nw")

How to custom button and text box using Python GUI?

I would like to ask how to make a custom button and custom text box by using Python?
A custom button should has: transparent feature with only border, round corner, shadow feature, icon need to be placed, animate feature like color changed when click and hover on it.
A custom text box should has: no border but only underline, round corner, transparent feature, icon need to be placed, animate feature like underline becomes thicker when click on it.
Below is my code:
frame = tk.Frame(root, bg='#000000', bd=0)
frame.place(relx=0.5, rely=0.1, relwidth=0.75, relheight=0.1, anchor='n')
entry = tk.Entry(frame, font=60, relief='flat')
entry.place(relwidth=0.65, relheight=1)
button = tk.Button(frame, text="Run", relief='flat', font=40, command=lambda: get_weather(entry.get()))
button.place(relx=0.7, relheight=1, relwidth=0.3)
Here is the reference image design that I prefer:
Any help would be appreciated, thanks!
Tkinter comes with the module ttk which stands for themed tk. It provides a way to create widget themes.
How to do it is under-documented, but tkdocs.com has a good discussion of the fundamentals.
At the end of this question is code which can create frames that have rounded corners, a shadow, and a unique color to represent focus, to serve as an example of what you can do. Answering all your questions is a bit beyond the scope of what stackoverflow is for, but hopefully, this is enough to show that what you want is possible.
import tkinter as tk
from tkinter import ttk
focusBorderImageData = '''
R0lGODlhQABAAPcAAHx+fMTCxKSipOTi5JSSlNTS1LSytPTy9IyKjMzKzKyq
rO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5G7QRdXxPoPkAnHfu+eeghw665n1vIKhJBQUEADs=
'''
root = tk.Tk()
style = ttk.Style()
borderImage = tk.PhotoImage("borderImage", data=borderImageData)
focusBorderImage = tk.PhotoImage("focusBorderImage", data=focusBorderImageData)
style.element_create("RoundedFrame",
"image", borderImage,
("focus", focusBorderImage),
border=16, sticky="nsew")
style.layout("RoundedFrame",
[("RoundedFrame", {"sticky": "nsew"})])
frame1 = ttk.Frame(style="RoundedFrame", padding=10)
text1 = tk.Text(frame1, borderwidth=0, highlightthickness=0, wrap="word",
width=40, height=4)
text1.pack(fill="both", expand=True)
text1.bind("<FocusIn>", lambda event: frame1.state(["focus"]))
text1.bind("<FocusOut>", lambda event: frame1.state(["!focus"]))
text1.insert("end", "This widget has the focus")
frame2 = ttk.Frame(style="RoundedFrame", padding=10)
text2 = tk.Text(frame2, borderwidth=0, highlightthickness=0, wrap="word",
width=40, height=4)
text2.pack(fill="both", expand=True)
text2.bind("<FocusIn>", lambda event: frame2.state(["focus"]))
text2.bind("<FocusOut>", lambda event: frame2.state(["!focus"]))
text2.insert("end", "This widget does not have the focus")
root.configure(background="white")
frame1.pack(side="top", fill="both", expand=True, padx=20, pady=20)
frame2.pack(side="top", fill="both", expand=True, padx=20, pady=20)
frame1.focus_set()
root.mainloop()
This code was originally posted as an answer to the question Tkinter: How to make a rounded corner text widget?. The original version of this code was written in Tcl in 2007, before stackoverflow existed.

Tkinter. How to change the background color of LabelFrame title?

I need to set a white background color of the LabelFrame title. I'm working on Tkinter in Python 3.6
Capture
You can specify your own widget to use as the LabelFrame's "label" — this mean, for example, you could create a separate Label widget with the text attributes you want, and specify it when creating the LabelFrame via the labelwidget= option:
import tkinter as tk
root = tk.Tk()
root.geometry('300x75')
label = tk.Label(root, text='Life, the universe and everything?', fg='white',
bg='blue')
lable_frame = tk.LabelFrame(root, labelwidget=label) # Use custom label.
lable_frame.pack(fill=tk.BOTH, expand=1, padx=5, pady=5)
w = tk.Entry(lable_frame)
w.pack(side=tk.LEFT, fill=tk.X, expand=1)
root.mainloop()
Result:

Tkinter Canvas Scrollbars stopped working

Intitially when the frame and canvas size were smaller both scrollbars worked fine. After I increased their size to match that of the Toplevel, the x scrollbar disappear and the y one stopped working.
You may say I don't need the x scrollbar, because I adjusted the canvas create_text width attribute to fit the text within the window, and you'd be right, but I am trying to learn how to use scrollbars when the window's maximize button is on and when it's off.
The files I load to read are pretty lengthy, so I need the y scrollbar to scroll all the way to the end of the text. Checking some online notes on the scrollregion, I came a cross one that suggested using n,e,w,s coordintates, but when I use them, I get errores. I used scrollregion=(0,0,500,500) but that seems too finite to me.
from tkinter import *
from tkinter import font
newline=''
fileContent=[]
filePath='file.txt'
lines=open(filePath)
newline=lines.read()
w=Tk()
def openViewer():
pop = Toplevel(w)
pop.title('Operation Report')
pop.geometry("750x500+15+20")
pop.state('zoomed') # Window's Miximize button
frame=Frame(pop,width=780,height=560)
frame.grid(row=0,column=0)
canvas=Canvas(frame, width=780, height=560, background='black')
canvas.config(scrollregion=(0,0,500,500))
canvas.pack(side=LEFT, fill=BOTH)
verdana_font = font.Font(family = "Verdana",size = 13)
canvas.create_text((30, 0), anchor='nw', text=newline,
font=verdana_font, fill = 'light grey',
justify=LEFT, width=750)
hbar=Scrollbar(frame,orient=HORIZONTAL)
hbar.pack(side=BOTTOM,fill=X)
hbar.config(command=canvas.xview)
vbar=Scrollbar(frame,orient=VERTICAL)
vbar.pack(side=RIGHT,fill=Y)
vbar.config(command=canvas.yview)
canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set)
btn=Button(w, text='View Content', command=openViewer)
btn.pack()
w.mainloop()
from tkinter import *
from tkinter import font
newline=''
fileContent=[]
filePath='C:/path to/ file.txt'
lines=open(filePath)
newline=lines.read()
w=Tk()
def openViewer():
pop = Toplevel(w)
pop.title('Operation Report')
pop.geometry("750x500+15+20")
pop.state('zoomed') # Window's Miximize button
frame=Frame(pop,width=780,height=560)
frame.grid(row=0,column=0)
# I decreased the canvas height to show the x scrollbar and removed
# the create_text method width attribute to unwrap the text and
# activate the horizontal scrollbar
canvas=Canvas(frame, width=780,height=530, background='black')
verdana_font = font.Font(family = "Verdana",size = 13)
canvas.create_text((0, 0), anchor='nw', text=newline,
font=verdana_font, fill = 'light grey',
justify=LEFT) # Add this width=750 to wrap text
hbar=Scrollbar(frame,orient=HORIZONTAL)
hbar.pack(side=BOTTOM,fill=X)
hbar.config(command=canvas.xview)
vbar=Scrollbar(frame,orient=VERTICAL)
vbar.pack(side=RIGHT,fill=Y)
vbar.config(command=canvas.yview)
canvas.config(scrollregion=canvas.bbox(ALL))
canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set)
canvas.pack(side=LEFT, expand=True, fill=BOTH)
btn=Button(w, text='View Content', command=openViewer)
btn.pack()
w.mainloop()
Hopefully, this may help someone else with the same or similar problem. :)

Vertical scrollbar for frame in Tkinter, Python

My aim is to have a scrollbar that stays at the right-side of a full-screen window, allowing the user to scroll up and down through various different widgets (such as labels & buttons).
From other answers I've seen on this site, I've come to the conclusion that a scrollbar has to be assigned to a canvas in order for it to function properly, which I have tried to include in my code but have not had much success with.
The below code shows a simplified version of what I've managed to accomplish so far:
from tkinter import *
root = Tk()
root.state("zoomed")
root.title("Vertical Scrollbar")
frame = Frame(root)
canvas = Canvas(frame)
Label(canvas, text = "Test text 1\nTest text 2\nTest text 3\nTest text 4\nTest text 5\nTest text 6\nTest text 7\nTest text 8\nTest text 9", font = "-size 100").pack()
scrollbar = Scrollbar(frame)
scrollbar.pack(side = RIGHT, fill = Y)
canvas.configure(yscrollcommand = scrollbar.set)
canvas.pack()
frame.pack()
root.mainloop()
I'm facing two issues when running this code:
One is that the scrollbar is inactive, and doesn't allow for the user to scroll down to view the rest of the text.
The other is that the scrollbar is attached to the right-side of the text, rather than the right-side of the window.
So far, none of the other answers I've found on this site have enabled me to amend my code to support a fully-functioning scrollbar for my program. I'd be very grateful for any help anyone reading this could provide.
See again link: https://stackoverflow.com/a/3092341/7432
It shows how to create scrolled frame - and then you can add all widgets in this frame.
import tkinter as tk
def on_configure(event):
# update scrollregion after starting 'mainloop'
# when all widgets are in canvas
canvas.configure(scrollregion=canvas.bbox('all'))
root = tk.Tk()
# --- create canvas with scrollbar ---
canvas = tk.Canvas(root)
canvas.pack(side=tk.LEFT)
scrollbar = tk.Scrollbar(root, command=canvas.yview)
scrollbar.pack(side=tk.LEFT, fill='y')
canvas.configure(yscrollcommand = scrollbar.set)
# update scrollregion after starting 'mainloop'
# when all widgets are in canvas
canvas.bind('<Configure>', on_configure)
# --- put frame in canvas ---
frame = tk.Frame(canvas)
canvas.create_window((0,0), window=frame, anchor='nw')
# --- add widgets in frame ---
l = tk.Label(frame, text="Hello", font="-size 50")
l.pack()
l = tk.Label(frame, text="World", font="-size 50")
l.pack()
l = tk.Label(frame, text="Test text 1\nTest text 2\nTest text 3\nTest text 4\nTest text 5\nTest text 6\nTest text 7\nTest text 8\nTest text 9", font="-size 20")
l.pack()
# --- start program ---
root.mainloop()
I would recommend using tkScrolledFrame
https://pypi.org/project/tkScrolledFrame/
They have a great little example on the website too. So easy to use and works great for me.
Below is a quick example:
from tkscrolledframe import ScrolledFrame
import tkinter as tk
# Create a root window
root = tk.Tk()
frame_top = tk.Frame(root, width=400, height=250)
frame_top.pack(side="top", expand=1, fill="both")
# Create a ScrolledFrame widget
sf = ScrolledFrame(frame_top, width=380, height=240)
sf.pack(side="top", expand=1, fill="both")
# Bind the arrow keys and scroll wheel
sf.bind_arrow_keys(frame_top)
sf.bind_scroll_wheel(frame_top)
frame = sf.display_widget(tk.Frame)
l = tk.Label(frame, text="Test text 1\nTest text 2\nTest text 3\nTest text 4\nTest text 5\nTest text 6\nTest text 7\nTest text 8\nTest text 9", font="-size 20")
l.pack()
root.mainloop()

Categories