How to update tkinter window every 4 seconds? - python

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:

Related

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?

Beginners Problem! NameError on python tkinter

New to python so this is probably a dumb question...
I want to say that if text1.get() == "1" then x = 0 and if text2.get() = "2" then y = 8. Then I want a button that adds x and y.
from tkinter import *
new = Tk()
new.title("Lockdown?")
new.geometry("700x400")
text3=Entry(new, width = "60")
text3.place(rely=0.15)
if text3.get() == "":
label9 = Label(new, text="required field", fg="red")
label9.place(rely=0.17)
elif text3.get() == "1":
x = "0"
elif text3.get() == "2":
x = "1"
elif text3.get() == "10":
x = "9"
else:
label10 = Label(new, text = "Please use a number ranging from 1-10")
text4=Entry(new, width = "60")
text4.place(rely=0.26)
if text4.get() == "":
label11 = Label(new, text="Required Field", fg = "red")
label11.place(rely=0.19)
elif text4.get() == "7":
y = "3"
elif text4.get() == "8":
y = "2"
elif text4.get() == "9":
y = "1"
elif text4.get() == "10":
y = "0"
else:
label11 = Label(new, text = "Please use a number ranging from 1-10")
def cmd3():
label15 = Label(new, text = x + y)
label15.place(rely=0.8)
btn3 = Button(new, text = "Submit Answers", command = cmd3, font=("Arial Bold", 25), bg = "white", fg = "black")
btn3.place(rely=0.71)
new.mainloop()
GUI frameworks (tkinter, PyQt, wxPython, etc., and in other languages) don't work like function input(). Entry doesn't wait for your data - it only inform mainloop what it has to display in window. And mainloop starts all - it displays window, etc. If you want to get value from Entry then you should do it in function assigned to Button.
My version with other changes
I use pack() instead of place() because it is simpler to organize widgets.
I create all labels at start (with empty text) and later I replace text in labels.
import tkinter as tk # PEP8: `import *` is not preferred
# --- functions ---
def cmd3():
# default value at start
x = None
y = None
# remove previous text
label1['text'] = ""
label2['text'] = ""
text = text1.get()
if text == "":
label1['text'] = "required field"
elif text == "1":
x = 0
elif text == "2":
x = 1
elif text == "10":
x = 9
else:
label1['text'] = "Please use a number ranging from 1-10"
text = text2.get()
if text == "":
label2['text'] = "required field"
elif text == "7":
y = 3
elif text == "8":
y = 2
elif text == "9":
y = 1
elif text == "10":
y = 0
else:
label2['text'] = "Please use a number ranging from 1-10"
print(x, y)
# it can't be `if x and y:` because `0` will gives `False`
if (x is not None) and (y is not None):
label_result['text'] = str(x + y)
# --- main ---
new = tk.Tk()
# empty at start
label1 = tk.Label(new, text="", fg="red")
label1.pack()
text1 = tk.Entry(new, width="60") # PEP8: arguments without spaces around `=`
text1.pack()
# empty at start
label2 = tk.Label(new, text="", fg="red")
label2.pack()
text2 = tk.Entry(new, width="60")
text2.pack()
btn3 = tk.Button(new, text="Submit Answers", command=cmd3)
btn3.pack()
# empty at start
label_result = tk.Label(new, text="", fg="green")
label_result.pack()
new.mainloop()

Why my code doesn't execute and how can I execute it?

It got executed once but I add some features and now it doesn't work anymore...
I'm a beginner at python and this is my first project. I'd like to create a game (which works perfectly in the console) but I have some troubles to put it with tkinter
If someone could take a look at this, it would be nice, thanks
Here's my code, I might have mistyped something or I don't know but I'm stucked with this and I can't find the mistake.
import tkinter as tk
from tkinter import Tk, Label, Canvas, Button, Frame, Toplevel, Entry
from random import randrange
num = randrange(0, 50)
money = 100
root = Tk()
root.geometry("750x750")
root["bg"]="beige"
label = Label(root, text="Welcome to the Casino")
label.place(width=180, x=300, y=300)
def csn(x, y, z, i):
if y < 50 and y >= 0 and z <= i :
if y == x:
i += z * 3
return "Well guess. You have %d" %(i)
elif (x % 2 == 0 and y % 2 == 0) or ( x % 2 != 0 and y % 2 != 0):
i += z * 0.5
return "Not so ba. You have %d" %(i)
else:
i -= z
return "Oops, Try again, you loose %d. You now have %d" %(z, i)
else:
return "Try again..."
def submit(master):
label1 = Label(master, text="try again...")
label1.place(width=180, x=300, y=300)
def casino():
top = Toplevel()
top['bg']= 'blue'
top.geometry = ('700x700')
root.withdraw
while money > 0:
try:
number_label = Label(top, text="Chose a nombre : ")
number_label.place(width=180, x=100, y=300)
nentry= Entry(top)
nentry.place(width=180, x=200, y=300)
number = int(nentry.get())
mise_label = Label(top, text="Entre the price you want to mise : ")
mise_label.place(width=180, x=100, y=400)
mise_entry = Entry(top)
mise_entry.place(width=180, x=200, y=400)
mise = float(mise_entry.get())
except ValueError:
btn3 = Button(top, text="submit", command=lambda : submit(top))
btn3.place(width=180, x=300, y=300)
btn = Button(top, text="submit", command= lambda : csn(num, number, mise, money))
btn.place(width=180, x=300, y=500)
else:
label2= Label(top, text="you lose")
label2.place(width=180, x=300, y=500)
btn1 = Button(top, text="Quit", command=top.quit)
btn1.place(width=180, x=300, y=400)
btn2 = Button(top, text="try again", command=casino)
btn2.place(width=180, x=200, y=400)
enter code here
button = Button(root, text="play!", relief='groove', command=casino)
button.place(width=180, x=300, y=400)
root.mainloop()

Zeller's Algorithm with Tkinter 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()

Tkinter Math Quiz

What is wrong with this program? Every time I run it the first math problem is show before I push start. Also the answer is always the first math problem, it never changes. Also there should not be a math problem above the timer. Thanks, Scott
from Tkinter import*
import time
import tkMessageBox
import random
def Questions():
number1 = random.randrange(1,25)
number2 = random.randrange(1,50)
answer = number1 + number2
prompt = ("Add " + str(number1) + " and " + str(number2))
label1 = Label(root, text=prompt, width=len(prompt), bg='yellow')
label1.pack()
return answer
def start():
global count_flag
Questions()
count_flag = True
count = 0.0
while True:
if count_flag == False:
break
# put the count value into the label
label['text'] = str(count)
# wait for 0.1 seconds
time.sleep(0.1)
# needed with time.sleep()
root.update()
# increase count
count += 0.1
def Submit(answer, entryWidget):
""" Display the Entry text value. """
global count_flag
count_flag = False
print answer
if entryWidget.get().strip() == "":
tkMessageBox.showerror("Tkinter Entry Widget", "Please enter a number.")
if answer != int(entryWidget.get().strip()):
tkMessageBox.showinfo("Answer", "INCORRECT!")
else:
tkMessageBox.showinfo("Answer", "CORRECT!")
# create a Tkinter window
root = Tk()
root.title("Math Quiz")
root["padx"] = 40
root["pady"] = 20
# Create a text frame to hold the text Label and the Entry widget
textFrame = Frame(root)
#Create a Label in textFrame
entryLabel = Label(textFrame)
entryLabel["text"] = "Answer:"
entryLabel.pack(side=LEFT)
# Create an Entry Widget in textFrame
entryWidget = Entry(textFrame)
entryWidget["width"] = 50
entryWidget.pack(side=LEFT)
textFrame.pack()
#directions
directions = ('Click start to begin. You will be asked a series of questions.')
instructions = Label(root, text=directions, width=len(directions), bg='orange')
instructions.pack()
# this will be a global flag
count_flag = True
answer = Questions()
Sub = lambda: Submit(answer, entryWidget)
#stopwatch = lambda: start(answer)
# create needed widgets
label = Label(root, text='0.0')
btn_submit = Button(root, text="Submit", command = Sub)
btn_start = Button(root, text="Start", command = start)
btn_submit.pack()
btn_start.pack()
label.pack()
# start the event loop
root.mainloop()
Your problem is with how you're calling the Questions() method. You only ask for the answer once with
answer = Questions()
and you do this before you press start (which is why it shows up before you hit start)
To fix it you could use code like this:
from Tkinter import*
import time
import tkMessageBox
import random
def Questions():
number1 = random.randrange(1,25)
number2 = random.randrange(1,50)
answer = number1 + number2
prompt = ("Add " + str(number1) + " and " + str(number2))
label1 = Label(root, text=prompt, width=len(prompt), bg='yellow')
label1.pack()
return answer
def start():
global count_flag
global answer
answer = Questions()
count_flag = True
count = 0.0
while True:
if count_flag == False:
break
# put the count value into the label
label['text'] = str(count)
# wait for 0.1 seconds
time.sleep(0.1)
# needed with time.sleep()
root.update()
# increase count
count += 0.1
def Submit(answer, entryWidget):
""" Display the Entry text value. """
global count_flag
count_flag = False
print answer
if entryWidget.get().strip() == "":
tkMessageBox.showerror("Tkinter Entry Widget", "Please enter a number.")
if answer != int(entryWidget.get().strip()):
tkMessageBox.showinfo("Answer", "INCORRECT!")
else:
tkMessageBox.showinfo("Answer", "CORRECT!")
# create a Tkinter window
root = Tk()
root.title("Math Quiz")
root["padx"] = 40
root["pady"] = 20
# Create a text frame to hold the text Label and the Entry widget
textFrame = Frame(root)
#Create a Label in textFrame
entryLabel = Label(textFrame)
entryLabel["text"] = "Answer:"
entryLabel.pack(side=LEFT)
# Create an Entry Widget in textFrame
entryWidget = Entry(textFrame)
entryWidget["width"] = 50
entryWidget.pack(side=LEFT)
textFrame.pack()
#directions
directions = ('Click start to begin. You will be asked a series of questions.')
instructions = Label(root, text=directions, width=len(directions), bg='orange')
instructions.pack()
# this will be a global flag
count_flag = True
Sub = lambda: Submit(answer, entryWidget)
#stopwatch = lambda: start(answer)
# create needed widgets
label = Label(root, text='0.0')
btn_submit = Button(root, text="Submit", command = Sub)
btn_start = Button(root, text="Start", command = start)
btn_submit.pack()
btn_start.pack()
label.pack()
# start the event loop
root.mainloop()
In this code the answer is updated every time you hit start and only updates when you hit start.

Categories

Resources