Anti-aliased fonts in tkinter? - python

Is there a way to get anti-aliased fonts in tkinter? If I increase the size of the default font like so:
default_font = tkFont.nametofont("TkDefaultFont")
default_font.configure(size=32)
the text comes out jagged.
Here is some version information:
Python 2.7.9 (default, May 6 2015, 09:33:48)
>>> Tkinter.__version__
'$Revision: 81008 $
I am using Gentoo Linux and have Tk 8.5 installed (which i believe should support anti-aliased fonts):
$ equery l tk
[IP-] [ ] dev-lang/tk-8.5.17:0/8.5
EDIT: adding this full MWE to describe what I'm doing:
from Tkinter import *
import tkFont
from ttk import *
root = Tk()
note = Notebook(root)
default_font = tkFont.nametofont("TkDefaultFont")
default_font.configure(size=48)
tab1 = Frame(note)
tab2 = Frame(note)
Button(tab1, text='Exit', command=root.destroy).pack(padx=100, pady=100)
note.add(tab1, text = "Curvy Words")
note.add(tab2, text = "Aliased")
note.pack()
root.mainloop()
exit()

It turns out to have been an issue with how tk was installed with gentoo. After adding truetype support by setting the use flag
For example, I added the line to /etc/portage/package.use
>=dev-lang/tk-8.5.17 truetype
And then remerged tk:
emerge -Na tk

I don't know much about ttk, but do know that you use "style" to set the font-->ttk tutorial http://www.tkdocs.com/tutorial/styles.html This looks fine on my Slackware box, but it uses anti-aliased by default.
from Tkinter import *
import ttk
import tkFont
root = Tk()
##default_font = tkFont.nametofont("TkDefaultFont")
##default_font.configure(size=48)
f = tkFont.Font(family='helvetica', size=24)
s = ttk.Style()
s.configure('.', font=f)
note = ttk.Notebook(root)
tab1 = ttk.Frame(note)
tab2 = ttk.Frame(note)
note.add(tab1, text = "Curvy Words")
note.add(tab2, text = "Aliased")
note.pack()
ttk.Style().configure("TButton", padding=6, relief="flat",
background="white")
ttk.Button(tab1, text='Exit', command=root.destroy).pack(padx=100, pady=100)
root.mainloop()

Related

Treeview moves after click on Combobox with Tkinter

I have developped a app in Python (tested with 3.8 and 3.9 on Windows 10) with Tkinter. I am using a Combobox and a Treeview. I want to change dynamically the width of dropdown listbox and I could do it by changing the style of TCombobox with the parameter postoffset.
However, everytime I click on the Combobox, the table next to it moves and extends its width by itself. I really don't know where this problem comes from.
I have created a simple code so that you can reproduce the problem.
import tkinter as tk
from tkinter import ttk
import tkinter.font as tkfont
def combo_configure(event, style):
combo = event.widget
long = max(combo.cget('values'), key=len)
font = tkfont.Font(family="Helvetica", size=10)
width = max(0,font.measure(long.strip() + '0') - combo.winfo_width())
style.configure('TCombobox', postoffset=(0,0,width,0))
win = tk.Tk()
win.geometry("850x250")
style = ttk.Style()
f = tk.Frame(win)
f.configure(bg="black")
f.pack()
combo = ttk.Combobox(f, style="TCombobox", values=["It's a test on Combobox style."], width=10)
combo.bind('<ButtonPress>', lambda e : combo_configure(e, style))
combo.pack(side="left")
tree = ttk.Treeview(f, column=["Column 1"], show='headings', height=10)
tree.heading(0, text="Column 1")
tree.column(0, anchor=tk.CENTER, width=125)
tree.pack()
win.mainloop()
Thanks.

Positioning text inside OptionMenu in tkinter python

hy I am working on tkinter python project.
I am trying to position text to the Left inside OptionMenu using anchor option but it does not seem to work. I am using ttk theme widgets.
Here is the code that I am trying currently.
s = ttk.Style()
s.configure('my.TMenubutton', font=("Cambria", fontSize, "bold"), background="white", anchor = W )
shapeMenu = ttk.OptionMenu(shapeFrame, shape, myShapes[1], *myShapes, style='my.TMenubutton', command=getShapes)
What I am doing wrong ?
It seems like there is no anchor option under TMenubutton. I tried TLabel, and it worked. Don't know if there is any side effect though.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.geometry('300x100')
CHART_TYPES = ('Reticle', 'Circle Grid', 'Checkerboard', 'Grille', 'Slanted Edge MTF')
s = ttk.Style()
s.configure('my.TLabel', font=("Cambria", 10, "bold"), background="white", anchor = 'w' )
chart_type = tk.StringVar()
chart_type.set(CHART_TYPES[0])
# chart_selector = tk.OptionMenu(root, chart_type, *CHART_TYPES)
chart_selector = ttk.OptionMenu(root, chart_type, *CHART_TYPES, style='my.TLabel')
# chart_selector.configure(anchor='w')
chart_selector.pack(expand=True, fill='x')
root.mainloop()

tkinter ttk treeview colored rows

I am trying to set colors to rows in a tkinter treeview object, using tags and tag_configure.
There has been an earlier discussion on coloring rows which is rather old and seems to work no longer for Python3:
ttk treeview: alternate row colors
I have added a brief example. For me, all rows stay white, independent of whether I execute tag_configure prior or after the insert command.
import tkinter as tk
import tkinter.ttk as ttk
root = tk.Tk()
w = tk.Label(root, text="Hello, world!")
w.pack()
lb= ttk.Treeview(root, columns=['number', 'text'], show="headings", height =20)
lb.tag_configure('gr', background='green')
lb.column("number", anchor="center", width=10)
lb.insert('',tk.END, values = ["1","testtext1"], tags=('gr',))
lb.insert('',tk.END, values = ["2","testtext2"])
lb.pack()
root.mainloop()
What has changed or what am I missing?
EDIT:
Seems that this is a new known bug with a workaround, but I don't get this working:
https://core.tcl-lang.org/tk/tktview?name=509cafafae
EDIT2:
I am now using tk Version 8.6.10 (Build hfa6e2cd_0, Channel conda-forge) and python 3.7.3. Can anyone reproduce this error with this version of python and tk?
You no longer need to use fixed_map the bug was fixed in tkinter version 8.6.
The following code works fine for me using tkinter 8.6 and python 3.8.2 running in Linux.
import tkinter as tk
import tkinter.ttk as ttk
def fixed_map(option):
return [elm for elm in style.map("Treeview", query_opt=option) if elm[:2] != ("!disabled", "!selected")]
root = tk.Tk()
style = ttk.Style()
style.map("Treeview", foreground=fixed_map("foreground"), background=fixed_map("background"))
w = tk.Label(root, text="Hello, world!")
w.pack()
lb= ttk.Treeview(root, columns=['number', 'text'], show="headings", height =20)
lb.tag_configure('odd', background='green')
lb.tag_configure('even', background='lightgreen')
lb.column("number", anchor="center", width=10)
lb.insert('', tk.END, values = ["1","testtext1"], tags=('odd',))
lb.insert('', tk.END, values = ["2","testtext2"], tags=('even',))
lb.insert('', tk.END, values = ["3","testtext3"], tags=('odd',))
lb.insert('', tk.END, values = ["4","testtext4"], tags=('even',))
lb.pack()
root.mainloop()
That answer of Chuck666 did the trick:
https://stackoverflow.com/a/60949800/4352930
This code works
import tkinter as tk
import tkinter.ttk as ttk
def fixed_map(option):
# Returns the style map for 'option' with any styles starting with
# ("!disabled", "!selected", ...) filtered out
# style.map() returns an empty list for missing options, so this should
# be future-safe
return [elm for elm in style.map("Treeview", query_opt=option)
if elm[:2] != ("!disabled", "!selected")]
root = tk.Tk()
style = ttk.Style()
style.map("Treeview",
foreground=fixed_map("foreground"),
background=fixed_map("background"))
w = tk.Label(root, text="Hello, world!")
w.pack()
lb= ttk.Treeview(root, columns=['number', 'text'], show="headings", height =20)
lb.tag_configure('gr', background='green')
lb.column("number", anchor="center", width=10)
lb.insert('',tk.END, values = ["1","testtext1"], tags=('gr',))
lb.insert('',tk.END, values = ["2","testtext2"])
lb.pack()
root.mainloop()
I hope that Chuck666 copies his answer here since I think he has earned the bonus if he shows up.

I need a separate frame, same as Python idle on tkinter window

I tried a lot to embedded the python idlw with my tkinter window. Is there any predefined module to embed idle with tkinter window?
# -*- coding: utf-8 -*-
## Front Homepage
from sklearn import linear_model
import matplotlib.pyplot as plt
from matplotlib import interactive
from login import *
from PIL import ImageTk, Image
import tkinter as tk
import os
from tkinter.ttk import *
##creating window
root = tk.Tk()
## Title bar of front page
program_name="Silk Project : SUPERVISED MODEL"
root.title(program_name)
root.configure(bg = "Pink")
## Menu Bar
menu_bar=Menu(root)
## File menu in menu bar
file_menu=Menu(menu_bar,tearoff=0)
menu_bar.add_cascade(label="File",menu=file_menu,underline=0)
file_menu.add_command(label="New",accelerator="Ctrl+N")
file_menu.add_command(label="Open",accelerator="Ctrl+O")
file_menu.add_command(label="Save",accelerator="Ctrl+S")
file_menu.add_command(label="Save as",accelerator="Shift+Ctrl+S")
file_menu.add_separator()
file_menu.add_command(label="Exit",accelerator="Alt+F4",)
root.config(menu=menu_bar)
## Edit menu in menu bar
Edit_menu=Menu(menu_bar,tearoff=0)
menu_bar.add_cascade(label="Edit",menu=file_menu,underline=0)
Edit_menu.add_command(label="New",accelerator="Ctrl+N")
Edit_menu.add_command(label="Open",accelerator="Ctrl+O")
Edit_menu.add_command(label="Save",accelerator="Ctrl+S")
Edit_menu.add_command(label="Save as",accelerator="Shift+Ctrl+S")
Edit_menu.add_separator()
Edit_menu.add_command(label="Exit",accelerator="Alt+F4",)
root.config(menu=menu_bar)
## Option menu in menu bar
Option_menu=Menu(menu_bar,tearoff=0)
menu_bar.add_cascade(label="Option",menu=file_menu,underline=0)
Option_menu.add_command(label="New",accelerator="Ctrl+N")
Option_menu.add_command(label="Open",accelerator="Ctrl+O")
Option_menu.add_command(label="Save",accelerator="Ctrl+S")
Option_menu.add_command(label="Save as",accelerator="Shift+Ctrl+S")
Option_menu.add_separator()
Option_menu.add_command(label="Exit",accelerator="Alt+F4",)
root.config(menu=menu_bar)
## FrAME A
s = Style()
s.configure('My.TFrame', background='plum1')
frame = Frame(root , style='My.TFrame')
frame.place(height=600, width=250, x=0, y=0)
## FrAME B
s1 = Style()
s1.configure('My2.TFrame', background='White')
frame2 = Frame(root , style='My2.TFrame')
frame2.place(height=590, width=950, x=250, y=15)
##Output Label
var="Output"
label1 = tk.Label(root , borderwidth = 10 , text=var , background="orange")
label1.place(height =15 , width =50 ,x=250,y=0)
## Size of Homepage
root.geometry("1200x600+50+25")
#not minimization and maximization property
root.resizable(0,0)
## Output Window :
from tkinter import *
from subprocess import *
print("Hello world")
def func():
proc = Popen("run.py", stdout=PIPE, stdin=PIPE ,stderr=PIPE , shell=True)
proc = proc.communicate()
output.insert(END, proc)
Check = Button(frame, text="Display output", command=func)
Quit = Button(frame, text="Exit", fg="red", command=root.quit)
output = Text(frame2)
Check.pack()
Quit.pack()
output.place(height=590, width=950, x=0, y=0)
root.iconbitmap(r'C:\Users\Silk\Desktop\SILK\SILK-GUI\5.ico')
root.mainloop()
No. IDLE is an application written in Python that uses tkinter. There are a few components that one might use in other applications, and might be more in the future, but they are subject to change and exernal use is not officially supported.

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