5

Question

How to create a rounded corner text widget? I think I have an idea of creating a rounded canvas and fill the entire canvas with the text box with no border.


Problem

The code to create a rounded border canvas is not working when I try to extend the height and width of the canvas. The line breaks and becomes discontinuous.


The code to create rounded corner canvas is taken from How to make a tkinter canvas rectangle with rounded corners?

My code with custom width and height

def rounded_rect(canvas, x, y, w, h, c):
    canvas.create_arc(x,   y,   x+2*c,   y+2*c,   start= 90, extent=90, style="arc")
    canvas.create_arc(x+w-2*c, y+h-2*c, x+w, y+h, start=270, extent=90, style="arc")
    canvas.create_arc(x+w-2*c, y,   x+w, y+2*c,   start=  0, extent=90, style="arc")
    canvas.create_arc(x,   y+h-2*c, x+2*c,   y+h, start=180, extent=90, style="arc")
    canvas.create_line(x+c, y,   x+w-c, y    )
    canvas.create_line(x+c, y+h, x+w-c, y+h  )
    canvas.create_line(x,   y+c, x,     y+h-c)
    canvas.create_line(x+w, y+c, x+w,   y+h-c)

import tkinter
root = tkinter.Tk()
canvas = tkinter.Canvas(root)
canvas.grid(row=0,column=0)

# The width and height has been changed from the original solution
rounded_rect(canvas, 10, 10, 330, 290, 10)
root.mainloop()

Output

enter image description here

Raj Mehta
  • 314
  • 1
  • 4
  • 20

3 Answers3

14

One solution is to use a ttk frame with a custom style that uses an image for the corners.

The following example is adapted from a tcl/tk solution I wrote back in 2007. It uses an odd color for the focus, and requires a white background, but you could create your own image to replace the one used in this solution (or edit the image in this example1)

enter image description here

# adapted from http://wiki.tcl.tk/%0920152
import tkinter as tk
from tkinter import ttk

focusBorderImageData = '''
    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
    Ry/99NIz//oGrZpUUEAAOw==
'''

borderImageData = '''
    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
'''

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()

1The image data is a base64-encoded gif. If you decode the data and save it to a .gif file, you can edit it to use any colors you want.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Thanks, Bryan. This is exactly what I needed for styling – Raj Mehta Jul 19 '18 at 15:49
  • @Bryan: FocusOut for text1 should also effect `frame1`. An edit of 1 character change is not allowed by non-author. – rioV8 Jul 20 '18 at 11:44
  • @Bryan: I have been looking for documentation of how to use `style.element_create` (`ttk::style element create`). But the tcl.tk website has not more info then that the method exists. Do you know where to find more information beside digging in the ttk source code? – rioV8 Jul 20 '18 at 12:28
  • @rioV8: this has some useful information: https://tkdocs.com/tutorial/styles.html – Bryan Oakley Jul 20 '18 at 12:30
  • @Bryan: Thanks. I have read this URL when I wanted to modify a layout and style. But it does not tell much about creating new styles from scratch other then it is possible. I will dig into the src code like the URL suggests at the bottom. – rioV8 Jul 20 '18 at 13:53
  • could you elaborate on how to change the background color of the image? I decoded it and put it into a .gif, then edited the background with paint, but the output has some weird black dots on the background color that do not appear in the paint version. Output: https://prnt.sc/18ycdc3 ,Paint version: https://prnt.sc/18yca1q – Viktor Stefanov Jul 06 '21 at 07:02
  • This code doest work if you put the frame on top of another frame – Charlie Zhang Jan 09 '22 at 14:30
  • @CharlieZhang: I don't know what you mean. It should work no matter whether you put it in another frame, on top of a frame, or anywhere else. – Bryan Oakley Jan 09 '22 at 16:41
5

Your canvas simply isn't large enough. Make it larger using

canvas = tkinter.Canvas(root, width=500, height=500)

Or make it resize with the root window using

canvas = tkinter.Canvas(root)
canvas.grid(row=0,column=0, sticky='NSEW')
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
fhdrsdg
  • 10,297
  • 2
  • 41
  • 62
  • It works. Thanks. And is this correct: How to create a rounded corner text widget? I think I have an idea of creating a rounded canvas and fill the entire canvas with the text box with no border. – Raj Mehta Jul 19 '18 at 15:00
0

I ran into this issue as well except for the main window. I was making a sticky notes app for someone and they wanted the window's corners to be rounded.

I had 4 canvases in the 4 corners with the image of an arc based on the corners. Then I made the color of those images transparent and it worked surprisingly well so I wanted to share it.

The four arcs

Rounded window

Here is the code:

from tkinter import *
from PIL import Image,ImageTk

def drag(event,win):
    x = win.winfo_pointerx() - win.offsetx
    y = win.winfo_pointery() - win.offsety
    win.geometry('+{x}+{y}'.format(x=x,y=y))

def click(event,win):
    win.offsetx = event.x
    win.offsety = event.y

root = Tk()
root.resizable(False,False)
root.geometry("610x260")
img = ImageTk.PhotoImage( Image.open("src/ARC.png").resize((150,150)), Image.ANTIALIAS )
img2 = ImageTk.PhotoImage( Image.open("src/ARC 2.png").resize((150,150)), Image.ANTIALIAS )
img3 = ImageTk.PhotoImage( Image.open("src/ARC 3.png").resize((150,150)), Image.ANTIALIAS )
img4 = ImageTk.PhotoImage( Image.open("src/ARC 4.png").resize((150,150)), Image.ANTIALIAS )
fr = Frame(root, bg = "yellow", bd = 0)
fr.pack( expand = True, fill = 'both')
canvas = Canvas(fr, bg = "yellow", width = 60, height = 60, bd=0, highlightthickness=0, relief='ridge')
canvas.create_image(-2,-2, image = img, anchor = "nw")
canvas2 = Canvas(fr, bg = "yellow", width = 60, height = 60, bd=0, highlightthickness=0, relief='ridge')
canvas2.create_image(62,-2, image = img2, anchor = "ne")
canvas3 = Canvas(fr, bg = "yellow", width = 60, height = 60, bd=0, highlightthickness=0, relief='ridge')
canvas3.create_image(-2,62, image = img3, anchor = "sw")
canvas4 = Canvas(fr, bg = "yellow", width = 60, height = 60, bd=0, highlightthickness=0, relief='ridge')
canvas4.create_image(62,62, image = img4, anchor = "se")
Grid.columnconfigure(fr, 0, weight = 1)
Grid.columnconfigure(fr, 1, weight = 1)
Grid.rowconfigure(fr, 1, weight = 1)
canvas.grid( row = 0, column = 0, sticky = 'NW' )
canvas2.grid( row = 0, column = 1, sticky = 'NE' )
canvas3.grid(row = 1, column = 0, sticky = 'SW' )
canvas4.grid(row = 1, column = 1, sticky = 'SE' )
root.overrideredirect(True)
root.wm_attributes('-transparentcolor', "#222222")
root.bind('<Button-1>', lambda e, root = root: click(e,root))
root.bind('<B1-Motion>', lambda e, root = root: drag(e,root))
root.mainloop()

Now you'd probably change the rows and columns of the canvases based on what you want inside the window but this is a good start.