0

Как сделать, чтобы при нажатии "Button" выводимый снизу текст полностью обновлялся, а не накладывался поверх старого?
root.update() и canvas.update() не помогают.

import random
import textwrap
import tkinter as tk
from PIL import ImageTk, Image

list = ["Вариант 1", "Вариант 2"]

path = 'background.jpg'

root = tk.Tk()
root.title('Тест')
root.resizable(height=False, width=False)
image = Image.open(path)
width = 410
height = 220
image = image.resize((width, height), Image.ANTIALIAS)
image = ImageTk.PhotoImage(image)

canvas = tk.Canvas(root, width=width, height=height)
canvas.pack(side="top", fill="both", expand="no")

canvas.create_image(0, 0, anchor="nw", image=image)

canvas.create_text(205, 35, text="Надпись", fill="#082745", font="Verdana 22 bold")

def output():
    text = random.choice(list)
    msg = textwrap.fill(text, width=45)
    canvas.create_text(205, 170, text=msg, font='Georgia', justify='center')

button = tk.Button(root, text='Кнопка', font="Verdana 18 bold", command=output)
canvas.create_window((150, 60), anchor="nw", window=button)

root.mainloop()

1 ответ 1

0

Можно создать текстовое поле с пустым полем text в основной программе, а в функции output просто случайным образом менять с помощью itemconfigure текст в этом элементе.

import random
import textwrap
import tkinter as tk
from PIL import ImageTk, Image

list = ["Вариант 1", "Вариант 2"]

path = 'background.jpg'

root = tk.Tk()
root.title('Тест')
root.resizable(height=False, width=False)
image = Image.open(path)
width = 410
height = 220
image = image.resize((width, height), Image.ANTIALIAS)
image = ImageTk.PhotoImage(image)

canvas = tk.Canvas(root, width=width, height=height)
canvas.pack(side="top", fill="both", expand="no")

canvas.create_image(0, 0, anchor="nw", image=image)

canvas.create_text(205, 35, text="Надпись", 
fill="#082745", font="Verdana 22 bold")

def output():
    text = random.choice(list)
    msg = textwrap.fill(text, width=45)
    canvas.itemconfigure(id, text=msg)


button = tk.Button(root, text='Кнопка', font="Verdana  
          18 bold", command=output)
id = canvas.create_text(205, 170, text="", 
font='Georgia', justify='center')
canvas.create_window((150, 60), anchor="nw", 
window=button)

root.mainloop()

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.