Python tkinter label обновление

How do I create an automatically updating GUI using Tkinter in Python?

GUI window has many controls such as labels, buttons, text boxes, etc. We may sometimes want the content of our controls such as labels to update automatically while we are viewing the window.

We can use after() to run a function after a certain time. For example, 1000 milliseconds mean 1 second. The function which we call continuously after a certain amount of time will update the text or any updation you want to happen.

We have a label on our window. We want the text of the label to update automatically after 1 second. To keep the example easy, suppose we want the label to show some number between 0 and 1000. We want this number to change after each 1 second.

We can do this by defining a function that will change the text of the label to some random number between 0 and 1000. We can call this function continuously after an interval of 1 second using the after().

Example

from Tkinter import * from random import randint root = Tk() lab = Label(root) lab.pack() def update(): lab['text'] = randint(0,1000) root.after(1000, update) # run itself again after 1000 ms # run first time update() root.mainloop()

This will automatically change the text of the label to some new number after 1000 milliseconds. You can change the time interval according to need. The update function can be modified to perform the required updation.

root.after(1000,update)

This line of the code performs the main function of recalling the function update().

The first parameter in root.after() specifies the time interval in milliseconds after which you want the function to be recalled.

The second parameter specifies the name of the function to be recalled.

Читайте также:  Document

Источник

How to update a Python/tkinter label widget?

Tkinter comes with a handy built-in functionality to handle common text and images related objects. A label widget annotates the user interface with text and images. We can provide any text or images to the label widget so that it displays in the application window.

Let us suppose that for a particular application, we need to update the label widget. A label widget is a container that can have either text of image. In the following example, we will update the label image by configuring a button.

Example

#Import the required library from tkinter import * from PIL import Image,ImageTk from tkinter import ttk #Create an instance of tkinter frame win= Tk() #Define geometry of the window win.geometry("750x450") #Define a Function to update to Image def update_img(): img2=ImageTk.PhotoImage(Image.open("logo.png")) label.configure(image=img2) label.image=img2 #Load the Image img1= ImageTk.PhotoImage(Image.open("logo1.png")) #Create a Label widget label= Label(win,image= img1) label.pack() #Create a Button to handle the update Image event button= ttk.Button(win, text= "Update", command= update_img) button.pack(pady=15) win.bind("", update_img) win.mainloop()

Output

Running the above code will display a window that contains a label with an image. The Label image will get updated when we click on the “update” button.

Now, click the «Update» button to update the label widget and its object.

Источник

Change the Tkinter Label Text

Change the Tkinter Label Text

  1. Use StringVar to Change/Update the Tkinter Label Text
  2. Label text Property to Change/Update the Python Tkinter Label Text

In this tutorial, we will introduce how to change the Tkinter label text when clicking a button.

Use StringVar to Change/Update the Tkinter Label Text

StringVar is one type of Tkinter constructor to create the Tkinter string variable.

After we associate the StringVar variable to the Tkinter widgets, Tkinter will update this particular widget when the variable is modified.

import tkinter as tk  class Test():  def __init__(self):  self.root = tk.Tk()  self.text = tk.StringVar()  self.text.set("Test")  self.label = tk.Label(self.root, textvariable=self.text)   self.button = tk.Button(self.root,  text="Click to change text below",  command=self.changeText)  self.button.pack()  self.label.pack()  self.root.mainloop()   def changeText(self):  self.text.set("Text updated")  app=Test() 
self.text = tk.StringVar() self.text.set("Test") 

The Tkinter constructor couldn’t initiate the string variable with the string like self.text = tk.StringVar() .

We should call set method to set the StringVar value, like self.text.set(«Test») .

self.label = tk.Label(self.root, textvariable=self.text) 

It associates the StringVar variable self.text to the label widget self.label by setting textvariable to be self.text . The Tk toolkit begins to track the changes of self.text and will update the text self.label if self.text is modified.

Читайте также:  Php field list error no 1054

The above code creates a Tkinter dynamic label. It automatically displays the Tkinter label text upon modification of self.text .

Label text Property to Change/Update the Python Tkinter Label Text

Another solution to change the Tkinter label text is to change the text property of the label.

import tkinter as tk  class Test():  def __init__(self):  self.root = tk.Tk()  self.label = tk.Label(self.root, text="Text")   self.button = tk.Button(self.root,  text="Click to change text below",  command=self.changeText)  self.button.pack()  self.label.pack()  self.root.mainloop()   def changeText(self):  self.label['text'] = "Text updated"  app=Test() 

The text of the label could be initiated with text=»Text» and could also be updated by assigning the new value to the text key of the label object.

We could also change the text property with the tk.Label.configure() method as shown below. It works the same with the above codes.

import tkinter as tk  class Test():  def __init__(self):  self.root = tk.Tk()  self.label = tk.Label(self.root, text="Text")   self.button = tk.Button(self.root,  text="Click to change text below",  command=self.changeText)  self.button.pack()  self.label.pack()  self.root.mainloop()   def changeText(self):  self.label.configure(text="Text Updated")  app=Test() 

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

Related Article — Tkinter Label

Источник

Python-сообщество

[RSS Feed]

  • Начало
  • » Python для новичков
  • » Циклическое обновление Label

#1 Окт. 6, 2019 01:12:41

Циклическое обновление Label

Здравствуйте, хочу сделать окошко, которое через заданный промежуток времени выводит новую строку из текстового файла. Файл это просто англо-русский словарь. Пытаюсь запрограммировать этот процесс используя цикл, но программа не работает. Дело осложняется тем, что примеры в интернете относятся к старым версиям Питона и толком не помогают. Подскажите, пожалуйста, каким образом проще всего это сделать? У меня версия Питона 3.7.4.

Читайте также:  Размеры шрифтов

import tkinter as tk
import time
f= open(“Dic.txt”,“r”, encoding=“utf-16”)
content = “test”
root = tk.Tk()

label1 = tk.Label(root, text= content)
label1.pack()

i = 1
while i < 1000:
content = f.readline(i)
time.sleep(1)
i = i + 1
root.update()

#2 Окт. 6, 2019 08:04:27

Циклическое обновление Label

Гораздо проще сделать без Tk. Будет у вас окошко — консоль и будут выводиться строки.

А то как вы делаете показывает что вы не понимаете как устроены любые GUI приложения и вам надо просто взять любую книжку и прочитать. Ну например http://oez.es/wxPython%20in%20Action.pdf

#3 Окт. 6, 2019 13:04:13

Циклическое обновление Label

Я действительно не понимаю, как устроены GUI) Но хотел бы разобраться для написания простых программ для себя. Идея с консолью хорошая, но нужно, чтобы окошко висело поверх других всегда, не скрывалось, не уверен что с консолью так получится, да и с Tк разобраться хочу. Тогда попробую спросить по другому. Какую версию Питона (выше 2-ой) легче всего будет изучить? Чтобы было много литературы и примеров? Установив самую свежую версию Питона я столкнулся с тем, что примеры программ созданные несколько лет назад просто не запускаются(( Для новичка это вызывает большие сложности. Сейчас поставил версию 3.5.1, посоветуйте книги под нее, кому не сложно.

#4 Окт. 6, 2019 14:34:57

Циклическое обновление Label

Вы не учли того, что каждый раз считывая строку из файла нужно обязательно её присвоить тексту в Label
Вот так будет работать

import tkinter as tk import time f= open("c:\\Dic.txt","r") content = "test" root = tk.Tk() label1 = tk.Label(root, text= content) label1.pack() for ln in f: label1["text"]=ln time.sleep(1) root.update() root.mainloop() f.close() 

#5 Окт. 6, 2019 18:45:10

Циклическое обновление Label

Artyom_N гуглите root.after()

#6 Окт. 6, 2019 19:48:00

Циклическое обновление Label

Спасибо за помощь. В итоге нашел программу секундомера и перепилил ее под словарь)) Такой код заработал для Питона 3.5.2, буду улучшать дальше:

from tkinter import *
f= open(“Dic.txt”,“r”, encoding=“utf-8”)
temp = 100
after_id = ‘’

def start_dic():
global temp, after_id
after_id = root.after(120000, start_dic)
content = f.readline(temp)
label1.configure(text = (content))
temp += 1

label1 = Label(root, font=“Arial 14”, width = 70,
height = 3, anchor=W)
label1.pack()

btn = Button(root, text=“go”, command = start_dic)
btn.pack()

#7 Окт. 6, 2019 20:44:51

Циклическое обновление Label

1. пжлст, форматируйте код, это в панели создания сообщений, выделите код и нажмите что то вроде
2. чтобы вставить изображение залейте его куда нибудь (например) , нажмите и вставьте ссылку на его url

есчщо

Источник

Оцените статью