Zeller's Algorithm with Tkinter Python - python

The code below is written to print out the day of the date wirtten which is called zellers algorithm. I tried to compile it with Tkinter but I get errors everytime.What is wrong with my code I would be glad if someone helps me. Error is:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1536, in __call__
return self.func(*args)
File "C:/Users/Ali/Desktop/zellers­revisited.py", line 60, in <lambda>
button = Tkinter.Button(zeller, text = "Show the day",command = lambda:zellers(A,B,C) )
File "C:/Users/Ali/Desktop/zellers­revisited.py", line 11, in zellers
D = int(str(C)[0:2])+1
ValueError: invalid literal for int() with base 10: ''
import math
import Tkinter
import tkMessageBox
dictionary = {"March": 1, "April":2, "May":3, "June":4, "July":5,"August":6, "September":7, "October":8, "November":9, "December":10 ,"January":11, "February":12}
def zellers(a,b,c):
a = int(str(c)[0:2])+1
a = int(dictionary[a])
a = int(str(c)[2:4])
w = ((13*a)-1) / 5
x = c / 4
y = d / 4
z = (w + x + y + b + c) - 2*d
r = z%7
if r == 0:
print "Sunday"
elif r == 1:
print "Monday"
elif r == 2:
print "Tuesday"
elif r == 3:
print "Wednesday"
elif r == 4:
print "Thursday"
elif r == 5:
print "Friday"
elif r == 6:
print "Sunday"
zeller = Tkinter.Tk()
month_label = Tkinter.Label(zeller ,text="Write the month: ")
entry1 = Tkinter.Entry()
a = entry1.get()
date_label = Tkinter.Label(zeller, text="Enter the date: ")
entry2 = Tkinter.Entry()
b = Entry2.get()
year_label = Tkinter.Label(zeller, text="Write the year: ")
entry3 = Tkinter.Entry()
c = Entry3.get()
button = Tkinter.Button(zeller, text = "Show the day",command = lambda:zellers(a,b,c) )
month_label.grid(row=0 , column=0)
entry1.grid(row=0, column=2)
date_label.grid(row=1, column=0)
entry2.grid(row=1, column=2)
year_label.grid(row=3, column=0)
entry3.grid(row=3, column=2)
button.grid(row=4, column=1)
zeller.mainloop()

The calls to get
Entry1 = Tkinter.Entry()
A = Entry1.get()
query the Entry widgets immediately, right after creation. Since they are empty at that point, A (and B and C) are empty strings.
You need to call get after zellers gets called:
def zellers():
A = Entry1.get()
B = Entry2.get()
C = Entry3.get()
...
import Tkinter
dictionary = {"March": 1, "April":2, "May":3, "June":4, "July":5,"August":6,
"September":7, "October":8, "November":9, "December":10 ,
"January":11, "February":12}
def zellers():
A = Entry1.get()
B = Entry2.get()
C = Entry3.get()
D = int(str(C)[0:2])+1
A = int(dictionary[A])
B = int(B)
C = int(str(C)[2:4])
W = ((13*A)-1) / 5
X = C / 4
Y = D / 4
Z = (W + X + Y + B + C) - 2*D
R = Z%7
result = {0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday',
5: 'Friday', 6: 'Saturday'}
print(result[R])
root = Tkinter.Tk()
month_label = Tkinter.Label(root ,text="Write the month: ")
Entry1 = Tkinter.Entry()
date_label = Tkinter.Label(root, text="Enter the date: ")
Entry2 = Tkinter.Entry()
year_label = Tkinter.Label(root, text="Write the year: ")
Entry3 = Tkinter.Entry()
button = Tkinter.Button(root, text = "Show the day", command=zellers)
month_label.grid(row=0, column=0)
Entry1.grid(row=0, column=2)
date_label.grid(row=1, column=0)
Entry2.grid(row=1, column=2)
year_label.grid(row=3, column=0)
Entry3.grid(row=3, column=2)
button.grid(row=4, column=1)
root.mainloop()

Related

TypeError: knapSack() missing 3 required positional arguments

I just start learning tkinter python for knapsack program. When I try to calculate, it doesn't do anything. And I am getting this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/tkinter/init.py", line 1921, in call
return self.func(*args)
TypeError: knapSack() missing 3 required positional arguments: 'W', 'wt', and 'val'
My code looks like this
import tkinter as tk
window = tk.Tk()
window.title("0/1 Knapsack")
canvas = tk.Canvas(window, height=1000, width=1000, bg = "#ADD8E6")
canvas.pack()
frame = tk.Frame(window, bg="white")
frame.place(relwidth=0.8, relheight=0.8,relx=0.1,rely=0.1)
def on_submit():
num_entries = int(num_entries_entry.get())
for i in range(num_entries):
Title_label = tk.Label(frame, text = "Items information")
Title_label.grid(row=5, column=1)
Title_label.config(font=("Arial", 18))
entry = tk.Entry(frame)
entry_label = tk.Label(frame, text = " Weight of items : " )
entry_label.grid(row=6,column=0)
entry.grid(row=7+i, column=0)
entry2 = tk.Entry(frame)
entry2_label = tk.Label(frame, text = " Value of each items")
entry2_label.grid(row=6, column=1)
entry2.grid(row=7+i, column=1)
capacity_label = tk.Label(frame, text =" Please select the capacity of your bag :")
capacity_spinbox = tk.Spinbox(frame, from_=1, to=100 )
capacity_label.grid(row=6, column=2)
capacity_spinbox.grid(row=7,column=2)
calculate_button =tk.Button(frame,text="Calculate", command = knapSack)
calculate_button.grid(row=7,column=3)
def calculate(weights, values, capacity):
result = knapSack(capacity, weights, values)
# Create a label to display the result
result_label = tk.Label(frame, text="Result: " + str(result))
result_label.grid(row=14, column=0)
def print_value_table(table):
print("Value Table:")
for row in table:
print(row)
def print_keep_table(table):
print("Keep Table:")
for row in table:
print(row)
def knapSack(W, wt, val):
n=len(val)
value_table = [[0 for x in range(W + 1)] for x in range(n + 1)]
keep_table = [[0 for x in range (W+1)] for x in range (n+1)]
for i in range(n + 1):
for j in range(W + 1):
if i == 0 or j == 0:
value_table[i][j] = 0
keep_table[i][j] = 0
elif wt[i-1] <= j:
if(val[i-1] + value_table[i-1][j-wt[i-1]]) > value_table[i-1][j]:
value_table[i][j] = val [i-1]+ value_table[i-1][j-wt[i-1]]
keep_table [i][j] = 1
else:
value_table[i][j] = value_table[i-1][j]
keep_table[i][j] = 0
else:
value_table[i][j] = value_table[i-1][j]
keep_table[i][j] = 0
print_value_table(value_table)
print_keep_table(keep_table)
return value_table[n][W]
num_entries_label = tk.Label(frame, text="Enter the number of items:")
num_entries_label.grid(row=1, column=1)
num_entries_entry = tk.Entry(frame)
num_entries_entry.grid(row=2, column=1)
next_button = tk.Button(frame, text="Next", command=on_submit)
next_button.grid(row=3, column=1)
title_label = tk.Label(frame, text = "Hi! Please follow the instructions!")
title_label.config(font=("Arial", 18))
window.mainloop()

suggestion with this error ->ValueError: x and y must have same first dimension, but have shapes (10,) and (1, 10)

I am creating a code that allows the user to enter 4 values (a, b, c, and d) for the equation (ax^3+bx^2+cx+d), then the program will output the graph on a window (I am using Tkinter). however, the code for some reason doesn't work.
To explain a bit my code in the input_check process I am outputting a button on a window with a blank box for the input. when the input is entered the program will check if it is the same as 3 (I will be adding more equations after (therefore it will check which equation the user wants), then it should asks for the values of a, b, c, and d, however after than it gives an error.
My code is:
from tkinter import *
import numpy as np
import matplotlib.pyplot as plt
root = Tk()
root.title("Maths Plot")
root.geometry("600x500")
root.configure(bg='dark blue')
# this function is just for fun at the moment
def foo():
print('working')
# navigation bar of the website
my_menu = Menu(root)
root.config(menu=my_menu)
# file menu
file_menu = Menu(my_menu)
my_menu.add_cascade(label='File', menu=file_menu)
file_menu.add_command(label='notebook', command=foo)
file_menu.add_command(label='open', command=foo)
file_menu.add_separator()
file_menu.add_command(label='copy', command=foo)
# edit menu
edit_menu = Menu(my_menu)
my_menu.add_cascade(label='Edit', menu=edit_menu)
edit_menu.add_command(label='add notebook', command=foo)
edit_menu.add_command(label='cell copy', command=foo)
edit_menu.add_separator()
edit_menu.add_command(label='paste cell', command=foo)
# checking which type of equation the user wants to enter on base of the number inputted
def input_check():
processing = FALSE
answer_int = int(answer1.get())
while processing == FALSE:
if answer_int == 1:
confirmation = Label(root, text="You have inputted the number 1")
confirmation.grid(row=3, column=1)
execution = Button(root, text="execute", command=linear_equation())
execution.grid(row=4, column=1)
processing = TRUE
elif answer_int == 2:
confirmation = Label(root, text="You have inputted the number 2")
confirmation.grid(row=3, column=1)
execution = Button(root, text="execute", command=quadratic_equation())
execution.grid(row=4, column=1)
processing = TRUE
elif answer_int == 3:
confirmation = Label(root, text="You have inputted the number 3")
confirmation.grid(row=3, column=1)
execution = Button(root, text="execute", command=cubic_equation())
execution.grid(row=4, column=1)
processing = TRUE
elif answer_int == 4:
confirmation = Label(root, text="You have inputted the number 4")
confirmation.grid(row=3, column=1)
execution = Button(root, text="execute", command=exponential_equation())
execution.grid(row=4, column=1)
processing = TRUE
else:
confirmation = Label(root, text="the answer you inputted is invalid, please try again.")
confirmation.grid(row=3, column=1)
label1 = Label(root, text="enter a number between 1 and 4 ")
answer1 = Entry(root)
button1 = Button(root, text='enter', command=input_check)
label1.grid(row=0, column=0)
answer1.grid(row=0, column=1)
button1.grid(row=1, column=1)
def linear_equation():
print("this is function 1")
def quadratic_equation():
print("this is function 2")
def cubic_equation():
a = ''
b = ''
c = ''
d = ''
# converting the Entries from string to float for future calcuations
def enter_click(event):
global a
global b
global c
global d
a = float(a_entry.get())
b = float(b_entry.get())
c = float(c_entry.get())
d = float(d_entry.get())
# code
x_axis = np.linspace(-10, 10, num=100)
y_base = [a * x_axis ** 3 + b * x_axis ** 2 + c * x_axis + d]
plt.figure(num=0, dpi=120)
plt.plot(x_axis, y_base, label="f(x)", linestyle='--')
plt.legend()
plt.grid(linestyle=':')
plt.xlim([-1000, 1000])
plt.ylim([-1000, 1000])
plt.title('graph')
plt.xlabel('x-axis')
plt.ylabel('y-axis')
a_entry = Entry(root)
a_entry.grid(row=5, column=0)
b_entry = Entry(root)
b_entry.grid(row=6, column=0)
c_entry = Entry(root)
c_entry.grid(row=7, column=0)
d_entry = Entry(root)
d_entry.grid(row=8, column=0)
enter_button = Button(root, text="Enter")
enter_button.grid(row=9, column=0)
enter_button.bind("<Button-1>", enter_click)
enter_button.bind("<Return>", enter_click)
'''def cubic():
return a * x_axis ** 3 + b * x_axis ** 2 + c * x_axis + d'''
def exponential_equation():
print("this is function 4")
root.mainloop()
the error that I keep getting is:
ValueError: x and y must have same first dimension, but have shapes (10,) and (1, 10)
I tried to search online for any information but I didn't find anything usefull.
(I found some solutions that use canvas but I have no idea on how to use it).
Can anyone help me please?

if a user enters a fraction as one of the values of the matrix that it will simply convert to float [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I want to fill in a matrix, and at the same time if a for example "1/7" get entered that it converts to float ? but it doesn't work
import fractions
import tkinter as tk
from tkinter import *
import numpy as np
import pandas as pd
from fractions import Fraction
from tkinter.font import Font
from PIL import Image, ImageTk
from PyQt5 import QtCore, QtGui, QtWidgets
import sqlite3
import tkinter.messagebox
import os
import sys
#this function contain a small window that you need to put the number of criteria in ,which will be the dimension of the maTRIX , WHEN I FILL THE matrix and click submit for it to be saved it doesn't work
def be():
window = Tk()
window.title("Dimensions ")
window.geometry("300x200")
def variable():
global fn, f
fn = entry_1.get()
f = entry_2.get()
ln = StringVar()
df = []
name = StringVar()
def save():
for entries in range(len(df)):
df[entries] = name.get()
for entries in range(len(df)):
df = df.append({'Critere': df[entries].get()}, ignore_index=True)
print(df)
df
def open_window():
root = tk.Tk()
root.geometry("460x600")
root.title('AHP Application ')
# global f
# f=printent()
# print(f)
for i in range(int(f)):
# c = input("Enter valeur {}: ".format(i))
my_label = Label(root, text="Entrer le critere numero 0{} :".format(i + 1), width=24, font=("bold", 10))
my_label.grid(row=i, column=0, pady=20, padx=5)
my_entry = Entry(root)
my_entry.grid(row=i, column=1, pady=20, padx=5)
df.append(my_entry)
suivant1 = tk.Button(root, text="Suivant", width=8, borderwidth=3, command=hope).place(x=370, y=40)
fermer2 = tk.Button(root, text="Fermer", width=8, borderwidth=3).place(x=370, y=90)
root.mainloop()
label_1 = Label(window, text="Entrer L'Objectif de Votre projet :", width=24, font=("bold", 10))
label_1.place(x=3, y=0)
entry_1 = Entry(window)
entry_1.place(x=100, y=30)
label_2 = Label(window, text="Entrer le nombre de critère :", width=20, font=("bold", 10))
label_2.place(x=3, y=70)
entry_2 = Entry(window)
# Remove default 0
entry_2.delete(0, END)
entry_2.place(x=100, y=100)
suivant = tk.Button(window, text="suivant", borderwidth=3, command=lambda: [variable(), open_window()]).place(x=40,
y=150)
fermer = tk.Button(window, text="fermer", borderwidth=3).place(x=190, y=150)
def hope():
win = Tk()
win.title("Matrix")
win.geometry("700x500")
global f
print(f)
wrapper1 = LabelFrame(win, text="Enter matrix")
wrapper3 = LabelFrame(win, text="Resultats")
wrapper1.pack(fill="both", expand="yes", padx=50, pady=20)
wrapper3.pack(fill="both", expand="yes", padx=20, pady=10)
def convert_to_float(frac_str):
try:
return float(frac_str)
except ValueError:
num, denom = frac_str.split('/')
try:
leading, num = num.split(' ')
whole = float(leading)
except ValueError:
whole = 0
frac = float(num) / float(denom)
return whole - frac if whole < 0 else whole + frac
# empty arrays for your Entrys and StringVars
text_var = []
entries = []
matrix = []
# callback function to get your StringVars
def get_mat():
for i in range(rows):
matrix.append([])
for j in range(cols):
matrix[i].append(convert_to_float (text_var[i][j].get()))
print(matrix)
b = np.array(matrix, dtype=float, order='C')
print(b)
global df2, df, c
index = []
columns = []
for i in range(int(f)):
index.append("critère{}".format(i + 1))
columns.append("critère{}".format(i + 1))
df = pd.DataFrame(data=b, index=index, columns=columns)
print(df)
arr = df.to_numpy()
global c
c = []
for i in range(len(df)):
c.append(np.prod(arr[i].astype(float)))
df2 = pd.DataFrame(data=c, index=range(int(f)), columns=["hi"])
print(df2)
# Label(win, text="Enter matrix :", font=('arial', 10, 'bold'),
# bg="bisque2").place(x=20, y=20)
x2 = 0
y2 = 0
rows = int(f)
cols = int(f)
global df2, df, c
x = np.array(['1.1', '2.2', '3.3'])
for i in range(rows):
# append an empty list to your two arrays
# so you can append to those later
text_var.append([])
entries.append([])
for j in range(cols):
# append your StringVar and Entry
text_var[i].append(StringVar())
entries[i].append(Entry(win, textvariable=text_var[i][j], width=5))
entries[i][j].place(x=80 + x2, y=30 + y2)
x2 += 40
y2 += 30
x2 = 0
button = Button(wrapper1, text="Submit", bg='bisque3', width=15, command=get_mat)
button.place(x=300, y=80)
my_label = Label(wrapper3, text="Lamda Max:", width=24, font=("bold", 10))
my_label.grid(row=0, column=0, pady=20, padx=5)
my_entry = Entry(wrapper3)
my_entry.grid(row=0, column=1, pady=20, padx=5)
# my_entry.insert(0,lamba)
my_label1 = Label(wrapper3, text="Indice de Coherence (CI):", width=24, font=("bold", 10))
my_label1.grid(row=1, column=0, pady=20, padx=5)
my_entry1 = Entry(wrapper3)
my_entry1.grid(row=1, column=1, pady=20, padx=5)
my_label2 = Label(wrapper3, text="Indice de Racio (IC):", width=24, font=("bold", 10))
my_label2.grid(row=2, column=0, pady=20, padx=5)
my_entry2 = Entry(wrapper3)
my_entry2.grid(row=2, column=1, pady=20, padx=5)
def calcule():
global f
df3 = pd.DataFrame(data=c, index=range(int(f)))
df3 = pow(df2, 1 / int(f))
print("df3 is ")
print(df3)
# Somme
Somme = df3.sum()
print("la somme est ")
print(Somme)
# weights
B = df3 / Somme
print(" La matrice des Poids:")
print(B)
# verify if somme of B is 1 , if it is then we are on the right road
Somm = B.sum()
print(Somm)
# consistency check
print("A3")
C = np.dot(df, B)
print(C)
# consistency check
print("A4")
D = C / B
print(D)
# global lamba
# Consistency Index
# lambda
lamba = np.mean(D)
print("the average is ")
print(lamba.to_string())
my_entry.insert(0, lamba.to_string(index=False))
# n = float(n)
CI = (lamba - float(f)) / (float(f) - 1)
print("The consistency Index is")
print(CI.to_string())
my_entry1.insert(0, CI.to_string(index=False))
# consistency ratio
if int(f) == 3:
RI = 0.52
elif int(f) == 4:
RI = 0.89
elif int(f) == 5:
RI = 1.11
elif int(f) == 6:
RI = 1.25
elif int(f) == 7:
RI = 1.35
elif int(f) == 8:
RI = 1.4
elif int(f) == 9:
RI = 1.45
elif int(f) == 10:
RI = 1.49
print("THE RATIO IS :")
print(RI)
CR = float(CI / RI)
my_entry2.insert(0, CR)
if CR < 0.1:
print("Congratulations ,Your criterias are consistent to go ahead \nThe value of consistency ratio is ",
CR,
"which is less han 0.1 ")
else:
print("you need to re-fill the matrix", CR)
button = Button(wrapper3, text="calcule", bg='bisque3', width=15, command=calcule)
button.place(x=500, y=100)
a = IntVar()
win.mainloop()
window.mainloop()
be()
Python actually has a built-in module just for this, which also has support for arbitrary-precision arithmetic and conversion to native floats.
>>> from fractions import Fraction
>>> frac = Fraction("1/7")
>>> float(fract)
0.14285714285714285
Easy to use, and works out-of-the-box. You can also convert it to an integer ratio, in case you want more accuracy than a native float can provide:
>>> frac.as_integer_ratio()
(1, 7)
The reason why float("1/7") doesn't work is because it's not a valid representation of an actual float: it's an integer ratio. Fractions, however, which provides native conversion to-and-from floats, does.

How to connect the Calculator GUI to the graph GUI?

I want to connect calculator gui with function graph gui.
For example
if I clicked 'sinx' on the calculator, the graph(which is sine function) would be apear on graph gui.
How could I do?
Calculator GUI code
from tkinter import *
window = Tk()
window.title("해대비주얼")
''
top_row = Frame(window)
top_row.grid(row=0, column=0, columnspan=2, sticky=N)
display = Entry(top_row, width=35, bg="light blue")
display.grid()
num_pad = Frame(window)
num_pad.grid(row=1, column=0, sticky=W)
num_pad_list = [
'7','8','9',
'4','5','6',
'1','2','3',
'0','.','=']
r = 0
c = 0
for btn_text in num_pad_list:
def cmd(x=btn_text):
click(x)
Button(num_pad, text=btn_text, width=5, command=cmd).grid(row=r, column=c)
c = c + 1
if c > 2:
c = 0
r = r + 1
operator = Frame(window)
operator.grid(row=1, column=1, sticky=E)
operator_list = [
'*','/',
'+','-',
'(',')',
'^','C']
r = 0
c = 0
for btn_text in operator_list:
def cmd(x=btn_text):
click(x)
Button(operator, text=btn_text, width=5, command=cmd).grid(row=r, column=c)
c = c + 1
if c > 1:
c = 0
r = r + 1
etc = Frame(window)
etc.grid(row=50, column=0, sticky=S)
etc_list = ['pi','sin','cos','x']
r = 0
c = 0
for btn_text in etc_list:
def cmd(x=btn_text):
click(x)
Button(etc, text=btn_text, width=5, command=cmd).grid(row=r, column=c)
r = 0
c = c + 1
def click(key):
if key == "=":
try:
if "^" in display.get():
n = display.get().split(sep="^")
result = str(float(n[0]) ** float(n[1]))
display.insert(END, " = " + result)
else:
result = str(eval(display.get()))[0:10]
display.insert(END, " = " + result)
except:
display.insert(END, " --> Error!")
elif key == "C":
display.delete(0, END)
elif key == etc_list[0]:
import math
display.insert(END, math.pi)
else:
display.insert(END, key)
window.mainloop()
2.Graph GUI code
from tkinter import *
graph = Tk()
graph.title("해대비주얼 그래프")
''
graph.geometry("1000x700")
''

How to update tkinter window every 4 seconds?

I am trying to create a program that reads lines from a file and puts them into a tkinter window. At the moment my code is this:
def read_notifications():
#def update():
# window.config(text=str(random.random()))
# window.after(1000, update)
aaa = 1
while True:
re = open("Y:/System Info/notifications.txt", "r")
rf = re.read()
rh = rf.count("\n")
re.close()
lines = [line.rstrip('\n') for line in open("Y:/System Info/notifications.txt")]
rk = -1
while True:
aaa = aaa + 2
rk = rk + 1
#print(lines[rk])
rl = rk + 1
ya = lines[rk].split("#")
yb = str(tomrt)
if ya[1] == yb:
yc = "Tommorow"
else:
if ya[1] == "0":
yc = "Monday"
if ya[1] == "1":
yc = "Tuesday"
if ya[1] == "2":
yc = "Wednesday"
if ya[1] == "3":
yc = "Thursday"
if ya[1] == "4":
yc = "Friday"
if ya[1] == "5":
yc = "Saturday"
if ya[1] == "6":
yc = "Sunday"
c = 650
window = tk.Tk()
#back = tk.Frame(width=700, height=c)
#back.pack()
window.title("Notifications")
window.iconbitmap("1235.ico")
#Subject
lbl = tk.Label(window, text=ya[0])
lbl.config(font=("Courier", 18))
lbl.grid(column=0, row=0)
#lbl.pack(side=tk.LEFT,)
#Day
lbl = tk.Label(window, text=" " + yc)
lbl.config(font=("Courier", 16))
lbl.grid(column=2, row=0)
#Type
lbl = tk.Label(window, text=ya[2])
lbl.config(font=("Courier", 16))
lbl.grid(column=4, row=0)
#Descripion
lbl = tk.Label(window, text=ya[4])
lbl.config(font=("Courier", 16))
lbl.grid(column=6, row=0)
#lbl.pack(side=tk.LEFT)
#window.after(1000, update)
if rl == rh:
print("hello")
break
if aaa > 2:
time.sleep(4)
window.destroy()
else:
window.mainloop()
I am not sure why this doesn't work properly. I am trying to make it so the tkinter window will update itself every 4 seconds, as another program is making changes to the notifications.txt file and I want the tkinter windows to update accordingly.
You code is a bit hard to re-work but here is a working example of how one can monitor a file.
Say I have a file that contains 4 lines and we call this file my_file:
1 test
2 testing
3 more testing
4 test again
All we want to do is update the labels ever 4 seconds so we can use the after() method to keep us going.
Take a look at this below code.
import tkinter as tk
window = tk.Tk()
window.title("Notifications")
file_to_monitor = "./my_file.txt"
def read_notifications():
with open(file_to_monitor, "r") as f:
x = f.read()
string_list = x.split("\n")
lbl1.config(text=string_list[0])
lbl2.config(text=string_list[1])
lbl3.config(text=string_list[2])
lbl4.config(text=string_list[3])
window.after(4000, read_notifications)
lbl1 = tk.Label(window, text="")
lbl1.grid(column=0, row=0, stick="w")
lbl2 = tk.Label(window, text="")
lbl2.grid(column=0, row=1, stick="w")
lbl3 = tk.Label(window, text="")
lbl3.grid(column=0, row=2, stick="w")
lbl4 = tk.Label(window, text="")
lbl4.grid(column=0, row=3, stick="w")
read_notifications()
window.mainloop()
What we start out with on the first read:
Then after I have made a change to the file and saved from my notepad:

Categories

Resources