Italicize tkinter label text on focus - python

I have a tkinter label
back_button = Label(self.about_frame, text = "Back", bg="black", fg="white", font=("Silkscreen", 18))
and I want to have the text's font change from regular to italic when a user hovers over the label with their mouse. How should I go about implementing this? Thanks!

import tkinter
from functools import partial
def font_config(widget, fontslant, event):
widget.configure(font=fontslant)
parent = tkinter.Tk()
text = tkinter.Label(parent, text="Hello Text")
text.bind("<Enter>", partial(font_config, text, "Helvetica 9 italic"))
text.bind("<Leave>", partial(font_config, text, "Helvetica 9"))
text.pack()
tkinter.mainloop()
See: this and this for more information.

Related

tkinter: how can I get the parameters (font, size, color, effect, etc...) of default font TkDefaultFont

I have an application where I need to know the parameters (font used: Arial, Calibri, etc..., size, color: foreground I believe in tkinter, effect: normal, bold, italic, etc..) of the default font TkDefaultFont used by my widgets.
Today I don't even know what color (foreground in tkinter) to go back to after I change it, since I have no way to "read" the present parameter settings.
I have an Entry widget and will validate the input. If the input is invalid, I will change the color (foreground) to red.
The code below tells you what I have done, what I know and don't know.
from tkinter import *
from tkinter import ttk
import tkinter.font as tkFont
def JMCheckButton2Command(*args):
if JMCheckButton2Variable.get()==1:
JMEntry.config(foreground = 'red')
else:
JMEntry.config(foreground = 'black')
####################### Tk() #######################
JMWindow = Tk()
s=ttk.Style()
print('\nTheme names are ', s.theme_names())
print('\nLayout of style TButton is:\n', s.layout('TButton'))
print('\nLayout of style TEntry is:\n', s.layout('TEntry'))
print("\nOptions available for element 'Button.label':\n",
s.element_options('Button.label'))
print("\nOptions available for element 'Entry.textarea':\n",
s.element_options('Entry.textarea'))
print("\nFont used in style 'TButton': ", s.lookup('TButton', 'font'))
print("\nFont used in style 'TButton': ", s.lookup('TEntry', 'font'))
####################### ttk.Frame #######################
JMFrame2=ttk.Frame(JMWindow, width='1i', height='2i', borderwidth='5',
relief='raised', padding=(5,5))
JMFrame2.grid()
####################### ttk.Entry #######################
JMEntryVariable = StringVar()
JMEntry = ttk.Entry(JMFrame2, textvariable=JMEntryVariable, width = 25)
JMEntry.insert(0, '100') # insert new text at a given index
####################### ttk.Label #######################
JMLabel2Text2Display = StringVar()
JMLabel2Text2Display.set('Enter number: ')
JMLabel2 = ttk.Label(JMFrame2, textvariable = JMLabel2Text2Display,
justify = 'center')
####################### ttk.Checkbutton #######################
JMCheckButton2Variable = IntVar()
JMCheckButton2=ttk.Checkbutton(JMFrame2, text='Change font color',
command = JMCheckButton2Command, variable = JMCheckButton2Variable)
JMLabel2.grid(column=0, row=0)
JMEntry.grid(column=1, row=0)
JMCheckButton2.grid(column=2, row=0, sticky = 'w', padx=25)
JMWindow.mainloop()
In general, Tk options/properties can be set #construction,
or later with calls to configure() / config().
What can be set with config(), can be queried with cget().
Can also index widgets with option names: widget['option']).
See tkinter sources, e.g. under: /usr/lib/python3.6/tkinter/
And Tcl/Tk documentation:
https://www.tcl.tk/man/tcl/TkCmd/contents.htm
For available options, you can search under:
https://www.tcl.tk/man/tcl/TkCmd/options.htm
and within:
/usr/lib/python3.6/tkinter/__init__.py
E.g. if you wanted to see options supported by class Button:
https://www.tcl.tk/man/tcl/TkCmd/button.htm
and within tkinter/__init__.py:
class Button(Widget):
"""Button widget."""
def __init__(self, master=None, cnf={}, **kw):
"""Construct a button widget with the parent MASTER.
STANDARD OPTIONS
activebackground, activeforeground, anchor,
...
import tkinter as tk
root = tk.Tk()
l = tk.Label(
root, text='asdf', font=('Times', 20)
)
l.pack()
tk.Button(
text='query font',
command=lambda: print(l.cget('font'))
).pack()
tk.Button(
text='change font',
command=lambda: l.configure(font=('Courier', 12))
).pack()
tk.Button(
text='query foreground',
command=lambda: print(l.cget('foreground'))
).pack()
tk.Button(
text='change foreground',
command=lambda: l.configure(foreground='#FF0000')
).pack()
root.mainloop()
Another example (different ways to get/set Tk options):
(See /usr/lib/python3.6/tkinter/font.py (has examples #end))
import tkinter as tk
from tkinter.font import Font # Access Font class directly.
from tkinter import font # To access 'weight' (BOLD etc.).
root = tk.Tk()
# printing f1 (without calling actual()) will print its name
f1 = Font(family='times', size=30, weight=font.NORMAL)
# printing f2 will print the tuple values
f2 = ('courier', 18, 'bold') # Can also use plain tuples.
# This will inlcude name for f1 (created with Font class),
# but not for f2 (f2 is just a tuple).
print('Names of currently available fonts:')
for fName in font.names(): print(fName)
label = tk.Label(root, text='Label Text', font=f1)
label.pack()
tk.Button(
text='Change font (config())',
command=lambda: label.config(font=f1)
).pack()
# Note: cannot use assignment inside lambda,
# so using ordinary function as callback here.
def changeFontWithMapNotation(): label['font'] = f2
tk.Button(
text='Change font (index map)',
command=lambda: changeFontWithMapNotation()
).pack()
tk.Button(
text='Read font (cget())',
command=lambda: print('font:', label.cget('font'))
).pack()
tk.Button(
text='Read font (index map)',
command=lambda: print('font:', label['font'])
).pack()
root.mainloop()
After looking around a bit into ttk source:
/usr/lib/python3.6/tkinter/ttk.py
and at the official docs:
https://www.tcl.tk/man/tcl/TkCmd/ttk_intro.htm
https://www.tcl.tk/man/tcl/TkCmd/ttk_style.htm
here is a ttk example, creating & using a minimal custom style:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
styleDb = ttk.Style(root)
csName = 'CustomLabelStyle'
# Need to define layout for custom style, before using it.
# Just copy the corresponding layout from ttk.
csLayout = styleDb.layout('TLabel')
styleDb.layout(csName, csLayout)
# Set ttk options, for custom style, in ttk style database.
styleDb.configure(
csName,
font=('Courier',18),
foreground='#22AA55',
background='#AA5522'
)
# Use custom style for specific widget.
label = ttk.Label(root, text='ttk label', style=csName)
label.pack()
ttk.Button(
root, text='default style',
command=lambda: label.config(style='TLabel')
).pack()
ttk.Button(
root, text='custom style',
command=lambda: label.config(style=csName)
).pack()
defaultLabelFont = styleDb.lookup('TLabel', 'font')
print(defaultLabelFont)
fontVar = tk.StringVar(root, styleDb.lookup(csName, 'font'))
ttk.Entry(root, textvariable=fontVar).pack()
ttk.Button(
root,text='set custom style font',
command=lambda: styleDb.configure(
csName, font=fontVar.get()
)
).pack()
root.mainloop()

Python Tkinter how can I place background text in a textbox?

I am trying to place a greyed out background text inside a textbox, that disappears when someone begins to type. I have tried overlaying a label onto the textbox, but I could not get it to work. Here is some code I am running for the text box
root = tk.Tk()
S = tk.Scrollbar(root)
T = tk.Text(root, height=70, width=50)
S.pack(side=tk.RIGHT, fill=tk.Y)
T.pack(side=tk.LEFT, fill=tk.Y)
S.config(command=T.yview)
T.config(yscrollcommand=S.set)
root.protocol("WM_DELETE_WINDOW", stop)
tk.mainloop()
How can I put in the background text?
Using a callback function you can remove the default text and change the foreground colour
import tkinter as tk
root = tk.Tk()
e = tk.Entry(root, fg='grey')
e.insert(0, "some text")
def some_callback(event): # must include event
e.delete(0, "end")
e['foreground'] = 'black'
# e.unbind("<Button-1>")
e.unbind("<FocusIn>")
return None
# e.bind("<Button-1>", some_callback)
e.bind("<FocusIn>", some_callback)
e.pack()
root.mainloop()
You are probably talking about placeholders , tkinter does not have placeholder attribute for Text widget, but you do something similar with Entry widget . You have to do it manually, by binding an event with the Text widget.
text = tk.StringVar()
text.set('Placeholder text')
T = tk.Entry(root, height=70, width=50, textvariable = text)
def erasePlaceholder(event):
if text.get() == 'Placeholder text':
text.set('')
T.bind('<Button-1>', erasePlaceholder)
Try to ask if you face any issues.

How to send information to a ScrolledText from a form in Tkinter with Python 3?

I made a form in Tkinter but when it is anwered I need the information to concatenate to a textbox.
Let's say I select I live in Chicago, how do I send that information to the scrolled text when I press the button "send"?
lblCd= Label(ventana,text="Location:",font= ("Arial", 20),
fg="blue", bg="white").place(x=70,y=400)
combo['values']=("Chicago","NY", "Texas")
combo.current(1)
combo.place(x=260, y=400)
Btn=Button(ventana, text="Send",)
Btn.place(x=200,y=500)
txt=scrolledtext.ScrolledText(ventana, width=40, height=10)
txt.place(x=260, y= 550)
txt.insert(INSERT, Nombre)
You can use Button(..., command=function_name) to execute function_name() when you press button. This function can get selected value and insert in scrolledtext.
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.scrolledtext as scrolledtext
def send_data():
txt.insert('end', combo.get() + '\n')
root = tk.Tk()
label = tk.Label(root, text="Location:")
label.pack()
combo = ttk.Combobox(root, values=("Chicago","NY", "Texas"))
combo.pack()
combo.current(0)
button = tk.Button(root, text="Send", command=send_data)
button.pack()
txt = scrolledtext.ScrolledText(root)
txt.pack()
root.mainloop()

How can I set the font and the colour for a Button's text in Tkinter?

This is my code below, The button's background is green, but I want to set the button text ("Done") to be white and 12 font.
from tkinter import *
def done(root):
root.destroy()
def panel():
root = Tk()
root.title("PCS Employee Login")
root.geometry('240x320+0+0')
root.configure(bg='white')
buttonDone = Button(root, text="Done", command=lambda: done(root))
buttonDone.configure(bg='green', borderwidth=0)
buttonDone.pack()
root.mainloop()
if __name__ == '__main__':
panel()
A Button's background is the button itself, and its foreground is the text or bitmap on top of it. Use the foreground option as described on Effbot.
This is an extract of code that I used for creating buttons and labels in tkinter. I create three font variables detailing small, normal and large font, then call these variables as needed. For the button and lable colours you can use bg for the background colour and fg for the foreground (text) colour.
LARGE_FONT = ("Verdana", 12)
NORM_FONT = ("Verdana", 10)
SMALL_FONT = ("Verdana", 8)
label = tk.Label(popup, text=msg, font=NORM_FONT, bg='white', justify='left')
B1 = tk.Button(popup, text="Okay", command=popup.destroy, bg='#000000', fg='#ffffff')
This page will give you more options for button configuration.

Underline Text in Tkinter Label widget?

I am working on a project that requires me to underline some text in a Tkinter Label widget. I know that the underline method can be used, but I can only seem to get it to underline 1 character of the widget, based on the argument. i.e.
p = Label(root, text=" Test Label", bg='blue', fg='white', underline=0)
change underline to 0, and it underlines the first character, 1 the second etc
I need to be able to underline all the text in the widget, I'm sure this is possible, but how?
I am using Python 2.6 on Windows 7.
To underline all the text in a label widget you'll need to create a new font that has the underline attribute set to True. Here's an example:
try:
import Tkinter as tk
import tkFont
except ModuleNotFoundError: # Python 3
import tkinter as tk
import tkinter.font as tkFont
class App:
def __init__(self):
self.root = tk.Tk()
self.count = 0
l = tk.Label(text="Hello, world")
l.pack()
# clone the font, set the underline attribute,
# and assign it to our widget
f = tkFont.Font(l, l.cget("font"))
f.configure(underline = True)
l.configure(font=f)
self.root.mainloop()
if __name__ == "__main__":
app = App()
For those working on Python 3 and can't get the underline to work, here's example code to make it work.
from tkinter import font
# Create the text within a frame
pref = Label(checkFrame, text = "Select Preferences")
# Pack or use grid to place the frame
pref.grid(row = 0, sticky = W)
# font.Font instead of tkFont.Fon
f = font.Font(pref, pref.cget("font"))
f.configure(underline=True)
pref.configure(font=f)
oneliner
mylabel = Label(frame, text = "my label", font="Verdana 15 underline")
Try this for underline:
mylbl=Label(Win,text='my Label',font=('Arial',9,'bold','underline'))
mylbl.grid(column=0,row=1)
mylabel = Label(frame, text = "my label")
mylabel.configure(font="Verdana 15 underline")
p = Label(root, text=" Test Label", bg='blue', fg='white', font = 'helvetica 8 underline')
put your own font (i choose helvetica 8)
To underline all the characters you should import tkinter.font and make your own font style with this. Example-
from tkinter import *
from tkinter.font import Font
rt=Tk()
myfont=Font(family="Times",size=20,weight="bold", underline=1)
Label(rt,text="it is my GUI".title(),font=myfont,fg="green").pack()
rt.mainloop()
should in this format:
dev_label=Label(Right_frame,text="purxxx#gmail.com", font=("Times",15,"bold italic underline"),fg="black",bg="white")
dev_label.place(x=80,y=120)

Categories