refreshText widget in tkinter - python

I try to create an update of my text widget in tkinter .
def affichage_update ():
with open('archives/monitor1_loc35L.txt') as monitor1, open('archives/monitor2_loc35L.txt') as monitor2:
s= Scrollbar(generalites)
T= Text(generalites,bg='powder blue',width=450,height=350,font=('arial',14,'bold'))
s.pack(side=RIGHT, fill=Y)
T.pack(side=LEFT, fill=Y)
s.config(command=T.yview)
T.config(yscrollcommand=s.set)
while True:
line1 = monitor1.readline()
if len(line1) == 0:
break
line1 = line1.strip().split()
line2 = monitor2.readline()
line2 = line2.strip().split()
T.insert(END, f'{line1[0]:15}\t {line1[1]:10}\t\t {line2[1]:10}\n')
T.after(1000, affichage_update)
affichage_update()
I would like help to find a solution to the automatic update of the content of my Text widget for example every 1 second
thanks

My answer should help you 2 ways here.
To show you what a minimum example looks like.
To provide some detail on how to use after().
Please in the future use a MCVE for questions. You will need your imports a root window and the minimum amount of code needed to reproduce the problem.
This example should help:
import tkinter as tk
generalites = tk.Tk()
s = tk.Scrollbar(generalites)
T = tk.Text(generalites)
s.pack(side="right", fill="y")
T.pack(side="left", fill="y")
s.config(command=T.yview)
T.config(yscrollcommand=s.set)
def affichage_update():
with open('archives/monitor1_loc35L.txt') as monitor1, open('archives/monitor2_loc35L.txt') as monitor2:
while True:
line1 = monitor1.readline()
if len(line1) == 0:
break
line1 = line1.strip().split()
line2 = monitor2.readline()
line2 = line2.strip().split()
T.insert("end", f'{line1[0]:15}\t {line1[1]:10}\t\t {line2[1]:10}\n')
T.after(1000, affichage_update)
affichage_update()
generalites.mainloop()

my code is so long and I have minimized it :
generalites is a tab of the notebook
so I think I can't write the last line : generalites.mainloop()
because there is'nt yet the end of my code
at the first picture, I must to write data into labelframe
add data into labelframe
and I will to recieve the informations and write it into text by textfiles
like this picture
data in Text widget

Related

changing label of tkinter in python

the code might be a little non-standart / messy. it's basically a guess the number game..
Any way, i want to change the label after the user pressing the yes/no button. i had some ideas but non of them worked well.. please help me :)
currently the label is "start from last time?" and i would like to change it to "choose a number between 1 - 99".
label = Label(root, text="start from last time?")
label.pack()
this is the function that activates when the user pressing the button, you can ignore what is written there just add the code :)
def yes():
fd = open("save.txt", "r")
data = fd.read()
data = data.split("|")
global answer
answer = int(data[0])
global attempts
attempts = int(data[1])
fd.close()
btnYes.pack_forget()
btnNo.pack_forget()
entryWindow.pack()
btnCheck.pack()
btnQuit.pack()
btnSave.pack()
root.geometry("500x150")
text.set("You Have {0} attempts Remaining! Good Luck!".format(attempts))
If what you are trying to do is to change the tk.Label text there are two ways to do it.
Label.config(text="Whaterver you want")
or
Label["text"] = "New Text"

How to create a letter counter with Tkinker?

I just started to learn Python and I'm trying to create a mineral counter by only using letters for microscopic petrography, but I am having problems passing my python code to Tkinker. Can you guys give tips about how to get my output to work? I'm finding it challenging to use theget() method even with online tutorials.
Can you guys teach this noob? Thank you!
My original code:
# define sample
sample = "qreqqwer"
# mineral q:
mineralq= "q"
countq = sample.count(mineralq)
# print count of q
print("The quantity of q is: ", countq)
The structure I made with Tkinker:
from tkinter import *
import tkinter as tk
# Window
window=tk.Tk()
window.title("Mineral Counter")
window.geometry("800x1000")
window.configure(bg="#00090F")
inputUser=tk.Text(window,width=225,height=5,font=("Arial bold",12),wrap="word", bg="#00090F", fg="white")
inputUser.pack()
# define sample
# mineral q:
countq = inputUser.count("q")
# print count of q
output.insert(tk.INSERT,countq)
output=tk.Text(window,width=20,height=2,font=("Arial bold",12), bg="#00090F", fg="white")
output.pack()
window.mainloop()
You need a button to update your code, becuase initially the Text boxes are empty and hence there is no occurence for q so nothing can be inserted.
Try this out:
First create a button with a function to click onto after the data is entered
b = tk.Button(window, text='Click Me', command=click)
b.pack()
Then now define the function that the button calls when is clicked onto
def click():
sample = inputUser.get('1.0', 'end-1c') #getting value from text box 1
mineralq = 'q' #letter to be counted
countq = sample.count(mineralq) #counting the letter
output.insert('1.0', f'The quantity of q is: {countq}') #inserting the output to text box 2
Hope it cleared your doubt, if any errors do let me know
Cheers

How To Clear a Label Assigned to a Grid in Specific Scenario Tkinter

I'm currently writing a manga reader and viewer program using the tkinter library in python for a gui, Im trying to make it so it lists the titles currently, and as I do this I realize its overlapping them, ive searched far and wide but wasnt able to find a good procedure to lets say "remove/forget" them on the new button press.
My code is listed below:
import json, webbrowser, requests
import tkinter as tk
from tkinter.ttk import *
from urllib import *
import urlopen
from urllib.request import *
import os
os.system("chcp 65001")
app = tk.Tk()
def get_button():
mid = entry.get()
if mid == "soap":
mid = "176758"
url = f"https://somewebsite/api/gallery/{mid}"
#label and pack for manga id
mangaid = tk.Label(text=f"ID : {mid}")
mangaid.grid(column=0, row=4, columnspan=2,)
#prints the url
print(url)
#open url data
uf = requests.request(method="get",url=url)
j_result = uf.json()
title = j_result['title']
j_title = title['japanese']
e_title = title['english']
#shows the title text
mangaide = tk.Label(text=f"English Title : {e_title}")
mangaidj = tk.Label(text=f"Japanese Title : {j_title}")
mangaide.grid(column=0, row=5, columnspan=2,)
mangaidj.grid(column=0, row=6, columnspan=2,)
def on_open():
mid = entry.get()
if mid == "soap":
mid = "176758"
URL = f"https://somewebsite.net/g/{mid}/"
#opens url
webbrowser.open(URL, new=2)
print(URL)
enterid = tk.Label(text="Enter ID or Name")
entry = tk.Entry()
button = tk.Button(text="Get", command=get_button)
button2 = tk.Button(text="Open", command=on_open)
enterid.grid(column=0, columnspan=2, pady=(10))
entry.grid(column=0, columnspan=2, padx=(50))
button.grid(row=3, column=0, pady=(10))
button2.grid(row=3,column=1)
app.mainloop()
If you look at lines 29-32 Im assigning a label and placing it on the grid, although when I press the button again, to get new data, it proceeds to do the following:
1st Data Grab
2nd Data Grab
In the first one you can see that it worked perfectly, but in the 2nd grab you can see that it took the previous answers and overlayed them behind, so in gist m trying to figure out a way to fix this, my main goal is to find a way to remove the overlayed text.
Im sorry if this isnt specific enough, if it isnt please contact me on discord (Ganoosh#4020) or through stack overflow comments.
Create empty Labels above app.mainloop() like this:
mangaide = tk.Label()
mangaidj = tk.Label()
mangaide.grid(column=0, row=5, columnspan=2,)
mangaidj.grid(column=0, row=6, columnspan=2,)
and put text on them inside get_button() function with the use of global keyword. Modify your get_button() function like this:
def get_button():
global mangaidj, mangaide # Using global keyword to access those Labels
mid = entry.get()
if mid == "soap":
mid = "176758"
url = f"https://somewebsite/api/gallery/{mid}"
#label and pack for manga id
mangaid = tk.Label(text=f"ID : {mid}")
mangaid.grid(column=0, row=4, columnspan=2,)
#prints the url
print(url)
#open url data
uf = requests.request(method="get",url=url)
j_result = uf.json()
title = j_result['title']
j_title = title['japanese']
e_title = title['english']
#shows the title text
mangaide.config(text=f"English Title : {e_title}") # These lines will
mangaidj.config(text=f"Japanese Title : {j_title}") # update the text each time
Hpoe this helps :)

How to loop through each word of ScrolledText and change the color of a word depending on which word it is?

I am making a text editor in tkinter for code, and I want to loop through every single word in the ScrolledText, and then change the color of it depending which word it is, but how?
I've already searched it up and found nothing that helped me. I also tried it on myself but I didn't know how to loop through the words forever (since while True made the program stop responding) and I don't know how to change the text color for only one bit.
This is all the code of my editor, some variables are defined in different functions:
def bie_save():
bie_file_read = open(bie_file,"r")
contents = bie_file_read.read()
bie_file_read.close()
data = text_area.get("1.0",tk.END + "-1c")
bie_file_file = open(bie_file,"w")
bie_file_file.write(data)
bie_file_file.close()
def builtin_editor(file,protype,proname):
global bie_file
bie_file = file
bie = tk.Tk()
bie.title("FIDE - Editor")
bie.geometry("800x450")
global text_area
text_area = st.ScrolledText(bie,width=800,height=450)
text_area.pack()
bie_file_read = open(bie_file,"r")
contents = bie_file_read.read()
bie_file_read.close()
text_area.insert("1.0",contents)
menu = tk.Menu(bie)
bie.config(bg=bg_theme,menu=menu)
fileMenu = tk.Menu(menu)
menu.add_cascade(label="File",menu=fileMenu)
fileMenu.add_command(label="Save",command=bie_save)
fileMenu.add_separator()
fileMenu.add_command(label="Exit")
bie.mainloop()
I want it like when you type "pass" it changes to orange or something like that, but if you type something else it won't.

How to store the input from the text box in python?

I want to make a program that show me the divisors of the number introduced in a text box using python tkinter GUI and store the results into a plain text file.
I don't how to get the value from the text box. I understood that is something linked with get() , I read something but I still don't get it.
Here is the code:
from tkinter import *
def create_file():
file_object = open("C:/Users/valis/Desktop/Divisors.txt","w+")
def evaluate():
show_after= Label(text= "Check your Desktop !")
show_after.pack(pady=2, anchor=SW)
create_file()
#Windows size and Title
window = Tk()
window.title("Show Divisors")
window.geometry("300x100")
message = Label(window, text="Enter a number : ")
message.pack(pady=2, anchor=NW)
textbox_input = Text(window,height=1, width=11)
textbox_input.pack(padx= 2,pady= 2, anchor=NW)
window.mainloop()
The code isn't complete, so what should I do ?
As you said, you will use the get() function but with some additional attributes.
If we have a text box textbox_input, then you can return its input using this line:
test_input = textbox_input.get("1.0",END)
The first part, "1.0" means that the input should be read from line one, character zero (ie: the very first character). END is an imported constant which is set to the string "end". The END part means to read until the end of the text box is reached.
Reference: This answer.

Categories