Tkinter:如何将文本小部件嵌入到画布小部件中

时间:2017-11-24 05:42:06

标签: python canvas tkinter

我想在tkinter中创建一个文本编辑器。首先,我创建了一个画布。然后,我想在画布中嵌入一个文本小部件,就像在图像中一样。

click to see image

我的代码如下:

def run():
    root = tk.Tk()
    global data
    class Struct(object): pass
    data = Struct()
    initData()
    global text
    text = Text(root,width=400,height=500)
    data.root = root
    canvas = Canvas(root,width=1200,height=600)
    canvas.pack()
    text.pack()
    drawBackground(canvas)
    root.mainloop()

run()

我应该如何编写文本的包语句而不是text.pack()

谢谢!

1 个答案:

答案 0 :(得分:1)

您必须使用canvas.create_window()代替text.pack() Text应使用canvas作为父级:Text(canvas)

BTW:width中的heightText位于chars,而不是pixels
对于不同的字体,Text将使用不同大小的像素。

import tkinter as tk

# --- classes ---

class Struct(object):
    pass

# --- functions ---

def run():
    # all `global` always at the top of function
    # to make it more readable
    global data
    global text

    data = Struct()
    #initData(data)

    root = tk.Tk()

    data.root = root

    canvas = tk.Canvas(root, width=1200, height=600)
    canvas.pack()
    #drawBackground(canvas)

    # Text needs `canvas` as parent.
    # `width` and `height` is in `chars`, not in `pixels`.
    # `Text` will use different size in pixels for different font.

    text = tk.Text(canvas, width=120, height=40)
    canvas.create_window((0, 0), window=text, anchor='nw')

    text.insert('end', 'Hello World')

    root.mainloop()

# --- main ---

run()

BTW:如果您想在背景中使用图片,那么您可以将Label与图片一起使用 然后,您可以TextLabel放在Label内作为父级。

import tkinter as tk
from PIL import ImageTk

# --- functions ---

def run():
    # all `global` always at the top of function
    # to make it more readable
    global text

    root = tk.Tk()

    image = ImageTk.PhotoImage(file='image.jpg')

    label = tk.Label(root, image=image)
    label.pack(fill='both', expand=True)
    label.image = image # keep reference - see Note on effbot.org 

    # Text needs `label` as parent
    # `padx`, `pady` create external margin so you can see background

    text = tk.Text(label)
    text.pack(fill='both', expand=True, padx=100, pady=100)

    text.insert('end', 'Hello World')    

    root.mainloop()

# --- main ---

run() 

BTW:请参阅注意关于“垃圾收集”并保持参考:Photoimage

enter image description here