- Tkinter — данные виджетов, присвоение и получение (insert, get, configure, delete) | Python GUI ч.6
- Полезные ссылки
- Установка значений виджетов (текст) в Tkinter
- Получение значений виджетов (текст) в Tkinter
- Get the Tkinter Label Text
- cget Method to Get text Option Value of Tkinter Label
- Complete Working Example of cget Method
- Read Value of Key text of Label Object Dictionary to Get Tkinter Label Text
- Complete Working Example
- Use StringVar to Get the Tkinter Label Text
- Related Article — Tkinter Label
- How to get the tkinter label text in Python?
- Method 1: Using the cget() method
- Method 2: Using the StringVar() method
- Step 1: Create a StringVar() object
- Step 2: Update the StringVar() object
- Complete code example
- Method 3: Using the Text() attribute
- Method 4: Using the get() method
Tkinter — данные виджетов, присвоение и получение (insert, get, configure, delete) | Python GUI ч.6
В предыдущей части моего сериала про Tkinter я разбирался с событиями и обработчиками событий. Однако суть пользовательского интерфейса также принимать данные пользователя и/или показывать данные пользователю. То есть при создании интерфейса на Python с помощью Tkinter я должен уметь передавать виджетам данные (для отображения) и получать данные из виджетов, полученные виджетом в результате пользовательского ввода.
Сегодня я покажу как работать с текстовыми данными в метках и полях ввода, однако, строго говоря, данными могут быть не только текст, но и изображения, положения мыши при клике, цвета, номера строк в списках и т.п., но сегодня только про текст.
В сегодняшнем видео передача данных и получение данных из виджетов Label и Entry. Также немного вспомним о позиционировании виджетов и их стилизации.
Полезные ссылки
- Документация Tk, где можно посмотреть options виджетов, в частности Label, Entry и Button.
- Методы виджета Entry.
- Список классов переменных для связывания StringVar, IntVar etc.
Установка значений виджетов (текст) в Tkinter
Способы передачи текстовых данных условно три штуки:
1. Через параметры при создании или через явную передачу значений в словарь настроек виджета
2. Через связывание с глобальной переменной классов Tkinter StringVar, IntVar, DoubleVar В этом случае содержимое виджета на экране обновляется автоматически при изменении связанной переменной.
3. С помощью методов некоторых виджетов (delete, insert)
Можно гуглить по запросам: tkinter configure , tkinter stringvar , tkinter intvar , tkinter text , tkinter texvariable .
Получение значений виджетов (текст) в Tkinter
1. Из словаря конфига
2. С помощью методов виджета (напр. get)
3. Из связанной переменной
Можно гуглить по запросам: tkinter textvariable , tkinter widget get , tkinter widget cget .
Get the Tkinter Label Text
- cget Method to Get text Option Value of Tkinter Label
- Read Value of Key text of Label Object Dictionary to Get Tkinter Label Text
- Use StringVar to Get the Tkinter Label Text
In this tutorial, we will introduce how to get the Tkinter Label text by clicking a button.
cget Method to Get text Option Value of Tkinter Label
Tkinter Label widget doesn’t have a specific get method to get the text in the label. It has a cget method to return the value of the specified option.
It returns the text property/opion of the Label object — labelObj .
Complete Working Example of cget Method
import tkinter as tk class Test(): def __init__(self): self.root = tk.Tk() self.root.geometry("200x80") self.label = tk.Label(self.root, text = "Text to be read") self.button = tk.Button(self.root, text="Read Label Text", command=self.readLabelText) self.button.pack() self.label.pack() self.root.mainloop() def readLabelText(self): print(self.label.cget("text")) app=Test()
Read Value of Key text of Label Object Dictionary to Get Tkinter Label Text
A label object is also a Python dictionary, so we could get its text by accessing the «text» key.
Complete Working Example
import tkinter as tk class Test(): def __init__(self): self.root = tk.Tk() self.root.geometry("200x80") self.label = tk.Label(self.root, text = "Text to be read") self.button = tk.Button(self.root, text="Read Label Text", command=self.readLabelText) self.button.pack() self.label.pack() self.root.mainloop() def readLabelText(self): print(self.label["text"]) app=Test()
Use StringVar to Get 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, we could get the text of the label by reading the value of StringVar variable.
import tkinter as tk class Test(): def __init__(self): self.root = tk.Tk() self.root.geometry("200x80") self.text = tk.StringVar() self.text.set("Text to be read") self.label = tk.Label(self.root, textvariable=self.text) self.button = tk.Button(self.root, text="Read Label Text", command=self.readLabelText) self.button.pack() self.label.pack() self.root.mainloop() def readLabelText(self): print(self.text.get()) app=Test()
get() method of StringVar variable returns its value, which is associated with the label text in this example.
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
How to get the tkinter label text in Python?
When working with the Tkinter library in Python, it is sometimes necessary to retrieve the text from a Label widget. This can be useful for updating the text in a Label or for checking the text that is currently being displayed. However, the process for getting the text from a Label can be slightly different than other Tkinter widgets, such as buttons or text boxes.
Method 1: Using the cget() method
To get the text of a Tkinter Label widget in Python, you can use the cget() method. Here’s how to do it:
import tkinter as tk root = tk.Tk() label = tk.Label(root, text="Hello, world!") label.pack()
text = label.cget("text") print(text) # Output: Hello, world!
You can also use cget() to get other properties of the Label, such as the font or foreground color:
font = label.cget("font") fg = label.cget("foreground") print(font) # Output: ('TkDefaultFont', 10) print(fg) # Output: black
That’s it! Using cget() is a simple way to get the properties of a Tkinter widget.
Method 2: Using the StringVar() method
To get the text of a Tkinter Label widget, we can use the text attribute of the widget. However, if we want to update the text dynamically, we can use the StringVar() method. Here’s how to do it:
Step 1: Create a StringVar() object
First, we need to create a StringVar() object and set its value to the initial text of the label:
import tkinter as tk root = tk.Tk() text_var = tk.StringVar() text_var.set("Hello, World!") label = tk.Label(root, textvariable=text_var) label.pack() root.mainloop()
In this example, we create a StringVar() object called text_var and set its value to «Hello, World!». We then create a Label widget called label and set its textvariable attribute to text_var .
Step 2: Update the StringVar() object
To update the text of the Label widget, we can simply update the value of the StringVar() object:
This will update the text of the Label widget to «New text!».
Complete code example
import tkinter as tk root = tk.Tk() text_var = tk.StringVar() text_var.set("Hello, World!") label = tk.Label(root, textvariable=text_var) label.pack() def update_text(): text_var.set("New text!") button = tk.Button(root, text="Update text", command=update_text) button.pack() root.mainloop()
In this example, we create a button that updates the text of the Label widget when clicked. When the button is clicked, the update_text() function is called, which updates the value of the text_var variable to «New text!». This, in turn, updates the text of the Label widget to «New text!».
Method 3: Using the Text() attribute
To get the text of a Tkinter Label widget using the Text() attribute, you can follow these steps:
import tkinter as tk root = tk.Tk() label = tk.Label(root, text="Hello World!") label.pack()
text = label.cget("text") print(text)
Alternatively, you can also use the textvariable attribute to get the text of the Label widget.
text_var = tk.StringVar() text_var.set("Hello World!") label = tk.Label(root, textvariable=text_var) label.pack() text = text_var.get() print(text)
That’s it! You have successfully retrieved the text of a Tkinter Label widget using the Text() attribute.
Method 4: Using the get() method
To get the text from a Tkinter Label widget in Python, you can use the get() method. Here’s how to do it:
from tkinter import * label = Label(text="Hello World") label.pack() text = label.get() print(text)
In this example, we create a Label widget with the text «Hello World». We then use the get() method to retrieve the text from the widget and store it in the text variable. Finally, we print the text to the console.
It’s important to note that the get() method only works for certain types of Tkinter widgets, including Labels and Entry widgets. For other types of widgets, you may need to use different methods to retrieve their values.
Here’s another example that demonstrates how to get the text from a Label widget when the user clicks a button:
from tkinter import * def get_label_text(): text = label.get() print(text) label = Label(text="Hello World") label.pack() button = Button(text="Get Label Text", command=get_label_text) button.pack() mainloop()
In this example, we define a function called get_label_text() that retrieves the text from the Label widget and prints it to the console. We then create a Button widget that calls this function when clicked. When the user clicks the button, the text from the Label widget is retrieved and printed to the console.
Overall, the get() method is a simple and effective way to retrieve the text from a Tkinter Label widget in Python. With a few lines of code, you can quickly access the text and use it in your application.