Python TTk simple if statement - ttk

I am new to Python, How can I can display the message "The water level is too high" only when the value of the first slide is above 80.00 ?
This is my try:
if value_label>80:
current_value_label99 = ttk.Label(
root,style="Red.TCheckbutton",
text='Water Level Too High!'
)
current_value_label99.grid(
row=7,
columnspan=2,
sticky='n',
ipadx=20,
ipady=20
)
enter image description here
Full code: https://jpst.it/31nkd

Related

Combine/Merge every x images together with title of each pict (linux)

I have some folders containing many jpg pictures (number depends on the folder)
I would like for instance to combine every 4 pict** together with the title of the image (see pict below).
(In case there is not exactly 4 image on the last sequence, I should get the number of left picture such as 3 2 or 1)
**Ideally I could change that number to other numbers like 5 6 10 (the number I chose would depend on the context) and I could chose the number of columns (I showed 2 column in my example below)
How can i perform this on Linux command or any Linux free/open-source software?
As I did not find what I want I created my own python code to solve this (it's probably not the most perfects script of the century but it works)
"""
Prints a collage according to desired number of column and rows with title of file
Instruction
1. Put all jpg picture in same folder [tested sucessfully on 12mb per pict]
2. select desired columns in NO_COL
3. select desired rowsin in NO_ROW
4. run the script which will output the collage with <cur_date>_export.png files
"""
#import libraries
import time
import os
import imageio as iio
from matplotlib import pyplot as plt
def render_collage(pict_file_name_list):
""" create one collage """
fig = plt.figure(figsize=(40, 28)) #change if needed
cnt = 1
for cur_img_name in pict_file_name_list:
img_var = iio.imread(cur_img_name)
fig.add_subplot(NO_COL, NO_ROW, cnt)
plt.imshow(img_var)
plt.axis('off')
plt.title(cur_img_name, fontsize = 30) #change if needed
cnt = cnt + 1
cur_date = time.strftime("%Y-%m-%d--%H-%M-%s")
fig.savefig(cur_date+'_export.png')
NO_COL = 3
NO_ROW = 3
NBR_IMG_COLLAGE = NO_COL * NO_ROW
img_list_name = [elem for elem in os.listdir() if 'jpg' in elem] #keep only file having .jpg
while len(img_list_name) >= 1:
sub_list = img_list_name[:NBR_IMG_COLLAGE]
render_collage(sub_list)
del img_list_name[:NBR_IMG_COLLAGE]

I want to create numbered array

I want to create an array using NumPy [ Dimension be User input, like (14402500)]. It must be scanned in both horizontal and vertical directions in certain window dimensions. For example, the array dimension is 1010, scanning window is 22. You can see in the image, this is for the vertical direction. and In the 2nd Image you can find the array in the Horizontal dimension.
this code executes for the dimension of (25402100) and window dimension of (2*2) it takes 8 to 9 seconds, I just want to optimize the code and I want to bring execution to 1 to 2 sec of the same dimension. Please help me.
I wrote a code, please go through this and help me to optimize the code
# Program for Creating Co-ordinates for Different dimensions array_ay
from datetime import datetime
from time import time
import time
from config import *
def dimension():
if direction=="v":
start=(time.time())
z=0
a=0
x=window_
res=[]
while a!=(array_/window_):
out=[]
for i in range(array_):
for j in range(z,x):
out.append((i,j))
if len(out)==(window_*window_):
res.append(out)
out=[]
a+=1
z+=window_
x+=window_
time_=str(time.time()-start)
return ( res, " Time of execution in sec: " , time_)
elif direction=="h":
start=(time.time())
z=0
a=0
x=window_
b=0
c=window_
res=[]
while a!=(array_/window_):
out=[]
for item in range(int(array_/window_)):
for i in range(b,c):
for j in range(z,x):
out.append((i,j))
if len(out)==(window_*window_):
res.append(out)
out=[]
x+=window_
z+=window_
x=window_
z=0
b+=window_
c+=window_
a+=1
time_=str(time.time()-start)
return (res , " Time of execution in sec: " , time_)
else:
print( "Please enter the valid letter!!")
print(dimension())

when i take input from user and wanna convert that input,the system errors

[enter image description here][1]
from word2number import w2n
w2n.word_to_num('one')
1
q = input('write your number letters : ')
>>>two
w2n.word_to_num('q')
>>>NameError: name 'two' is not defined
i use word2number package to convert word to number, like; two = 2. when i take input from user and wanna convert that input,the system errors.
Please post the full code as text that you are trying that is giving you errors.
But the code from the Word2number documentation is working fine for me.
https://pypi.org/project/word2number/
Python 3
from word2number import w2n
print(w2n.word_to_num('point one'))
Output:
0.1
Python 2
from word2number import w2n
print w2n.word_to_num('point one')
Output:
0.1

Reading Keystrokes and Placing into Textbox

I am a teacher that is writing a program to read an 8-digit ID barcode for students who are late to school. I am an experienced programmer, but new to Python and very new to Tkinter (about 36 hours experience) I have made heavy use of this site so far, but I have been unable to find the answer to this question:
How can I read exactly 8 digits, and display those 8 digits in a textbox immediately. I can do 7, but can't seem to get it to 8. Sometimes, I will get nothing in the text box. I have used Entry, bind , and everything works OK, except I can't seem to get the keys read in the bind event to place the keys in the textbox consistently that were inputted. The ID seems to be always correct when I PRINT it, but it is not correct in the textbox. I seem unable to be allowed to show the tkinter screen, so it shows only 7 digits or nothing in the text box upon completion.
Here is a snippet of my code, that deals with the GUI
from tkinter import *
from collections import Counter
import time
i=0
class studentNumGUI():
def __init__(self, master):
master.title("Student ID Reader")
self.idScanned = StringVar()
localTime = time.asctime(time.localtime(time.time()))
self.lblTime = Label(master, text=localTime)
self.lblTime.pack()
self.lbl = Label(master, text="Enter Student ID:")
self.lbl.pack()
self.idScanned.set("")
self.idScan = Entry(master,textvariable=self.idScanned,width=12)
self.idScan.pack()
self.frame=Frame(width=400,height=400)
self.frame.pack()
self.frame.focus()
self.frame.bind('<Key>',self.key)
def key(self,event):
global i
self.frame.focus()
self.idScan.insert(END,event.char)
print(repr(event.char)," was pressed") #just to make sure that my keystrokes are accepted
if (i < 7):
i += 1
else:
#put my other python function calls here once I fix my problem
self.frame.after(2000)
#self.idScan.delete(0,END) #Then go blank for the next ID to be read
i=0
root = Tk()
nameGUI = studentNumGUI(root)
root.mainloop()
enter image description here
You are doing some unusual things in order to place text inside the Entry field based on keypresses. I've changed your code so that it sets the focus on the Entry widget and will check the contents of the Entry field each time a key is pressed (while the Entry has focus). I'm then getting the contents of the Entry field and checking if the length is less than 8. If it is 8 (or greater) it will clear the box.
How does this work for you?
I've left in the commented out code
from tkinter import *
from collections import Counter
import time
class studentNumGUI():
def __init__(self, master):
master.title("Student ID Reader")
self.idScanned = StringVar()
localTime = time.asctime(time.localtime(time.time()))
self.lblTime = Label(master, text=localTime)
self.lblTime.pack()
self.lbl = Label(master, text="Enter Student ID:")
self.lbl.pack()
self.idScanned.set("")
self.idScan = Entry(master,textvariable=self.idScanned,width=12)
self.idScan.pack()
self.idScan.focus_set()
self.frame=Frame(width=400,height=400)
self.frame.pack()
#self.frame.focus()
#self.frame.bind('<Key>',self.key)
self.idScan.bind('<Key>',self.key)
def key(self,event):
#self.frame.focus()
#self.idScan.insert(END,event.char)
print(repr(event.char)," was pressed") #just to make sure that my keystrokes are accepted
len(self.idScanned.get())
if (len(self.idScanned.get())<8):
pass
else:
#put my other python function calls here once I fix my problem
self.idScan.delete(0,END) #Then go blank for the next ID to be read
#self.frame.after(2000)
root = Tk()
nameGUI = studentNumGUI(root)
root.mainloop()

Pygal bar chart says "No Data"

I am trying to create a bar graph in pygal that uses the api for github and charts the most popular projects based on stars. I posted my code below, but I cannot figure out why my graph keep saying "No Data"??? Any suggestions? Thanks!
import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code:", r.status_code)
response_dict = r.json()
print('Total repositories:', response_dict['total_count'])
repo_dicts = response_dict['items']
names,stars = [],[]
for repo_dict in repo_dicts:
names.append(repo_dict['name'])
stars.append(repo_dict['stargazers_count'])
my_style = LS('#333366',base_style=LCS)
chart = pygal.Bar(style=my_style,x_label_rotation=45,show_legend=False)
chart.title = 'Most Starred Python Projects on GitHub'
chart.x_labels = names
chart.add = ('',stars)
chart.render_to_file('python_repos.svg')
on the second last line of your code, chart.add=('',stars) there should not be a '=' equal sign there , it should be chart.add('',stars) then the code should work! :)

Resources