Tkinter, PyAutoGUI Python - python

He everyone! I have one problem and I hope you will help me with that.
I am doing window with question and I want to get the text from Entry.
When I am getting that (I am using 'EntryValue = EntryName.get()') it isn't giving error, but when I want to print it with
PyAutoGUI.typewrite(EntryValue) it isn't print that because there isn't any value
in my variable.
That is my code:
**from tkinter import *
import pyautogui as pg
import time
EntryThatAnswersToQuestionValue = ""
def FunctionThatCreatesWindowThatFindsProgramm():
WindowThatFindsProgram = Toplevel(Root)
WindowThatFindsProgram.iconbitmap(r'C:\Users\Murad\Desktop\My Factory\Programmes\J.A.R.V.I.S\Icon\QuestionIcon.ico')
WindowThatFindsProgram.title("J.A.R.V.I.S. Has a question.")
WindowThatFindsProgram.geometry('350x250')
LabelThatExplainsWhatToDoInWindowThatFindsProgram = Label(WindowThatFindsProgram,text="Please, write your programm's name sir."
,fg='black',font='Arial 10 bold')
LabelThatExplainsWhatToDoInWindowThatFindsProgram.pack()
EntryThatAnswersToQuestion = Entry(WindowThatFindsProgram)
EntryThatAnswersToQuestion.pack()
EntryThatAnswersToQuestionValue = EntryThatAnswersToQuestion.get()
OKButton = Button(WindowThatFindsProgram,text=" OK ",fg='black',font='Arial 10 bold',command=FunctionThatFindsProgramm)
OKButton.pack()
def FunctionThatFindsProgramm():
pg.hotkey('winleft')
time.sleep(1)
pg.typewrite(EntryThatAnswersToQuestionValue,3)
time.sleep(1)
pg.hotkey('enter')**
Root = Tk()
Root.iconbitmap(r'C:\Users\Murad\Desktop\My Factory\Programmes\J.A.R.V.I.S\Icon\Icon.ico')
Root.title("J.A.R.V.I.S.")
Root.geometry('960x540')
Root['bg'] = 'black'
MainMenu = Frame(Root,bg='black')
MainMenu.pack()
JarvisTextGreeting = Label(MainMenu,text="Hello, sir. You can tell the below commands for execution.",bg='black'
,fg='blue',font='Arial 15 bold')
JarvisTextGreeting.pack()
ButtonFindingTheProgramm = Button(MainMenu,text="J.A.R.V.I.S. Please find programm that I will tell you on my PC"
,bg='blue',fg='black',font='Arial 10 bold',command=FunctionThatCreatesWindowThatFindsProgramm)
ButtonFindingTheProgramm.pack()
Root.mainloop()

You have to take the variable as global variable in the function:
from tkinter import *
import pyautogui as pg
import time
EntryThatAnswersToQuestionValue = ""
def FunctionThatCreatesWindowThatFindsProgramm():
global EntryThatAnswersToQuestionValue
WindowThatFindsProgram = Toplevel(Root)
WindowThatFindsProgram.iconbitmap(r'C:\Users\Murad\Desktop\My Factory\Programmes\J.A.R.V.I.S\Icon\QuestionIcon.ico')
WindowThatFindsProgram.title("J.A.R.V.I.S. Has a question.")
WindowThatFindsProgram.geometry('350x250')
LabelThatExplainsWhatToDoInWindowThatFindsProgram = Label(WindowThatFindsProgram,text="Please, write your programm's name sir."
,fg='black',font='Arial 10 bold')
LabelThatExplainsWhatToDoInWindowThatFindsProgram.pack()
EntryThatAnswersToQuestion = Entry(WindowThatFindsProgram)
EntryThatAnswersToQuestion.pack()
EntryThatAnswersToQuestionValue = EntryThatAnswersToQuestion.get()
OKButton = Button(WindowThatFindsProgram,text=" OK ",fg='black',font='Arial 10 bold',command=FunctionThatFindsProgramm)
OKButton.pack()
def FunctionThatFindsProgramm():
pg.hotkey('winleft')
time.sleep(1)
pg.typewrite(EntryThatAnswersToQuestionValue,3)
time.sleep(1)
pg.hotkey('enter')
Root = Tk()
Root.iconbitmap(r'C:\Users\Murad\Desktop\My Factory\Programmes\J.A.R.V.I.S\Icon\Icon.ico')
Root.title("J.A.R.V.I.S.")
Root.geometry('960x540')
Root['bg'] = 'black'
MainMenu = Frame(Root,bg='black')
MainMenu.pack()
JarvisTextGreeting = Label(MainMenu,text="Hello, sir. You can tell the below commands for execution.",bg='black'
,fg='blue',font='Arial 15 bold')
JarvisTextGreeting.pack()
ButtonFindingTheProgramm = Button(MainMenu,text="J.A.R.V.I.S. Please find programm that I will tell you on my PC"
,bg='blue',fg='black',font='Arial 10 bold',command=FunctionThatCreatesWindowThatFindsProgramm)
ButtonFindingTheProgramm.pack()
Root.mainloop()

Related

Python script using Tkinter for displaying sensor readings over background image displaying correctly

So I'm making a script for a raspberry pi 3-b. The idea is to take sensor readings from 4 sensors, and display each reading, updating over time, in each corner overtop of a background image. I am mostly unfamiliar with python, and new to tkinter.
The following is my current code.
from tkinter import *
from PIL import ImageTk
import Adafruit_DHT
import tkinter as tk
from tkinter import font as tkfont
window = Tk()
def main():
c = Canvas(window,height=480,width=800)
image = ImageTk.PhotoImage(file="/home/pi/Desktop/AppFiles/AppBackround.jpg")
c.create_image(0,0,image=image,anchor=NW)
text1 = tk.StringVar()
text2 = tk.StringVar()
text3 = tk.StringVar()
text4 = tk.StringVar()
myFont = tkfont.Font(family="Titillium Web", size=32)
c.create_text(10,10,text=text1,fill="yellow",font=myFont)
c.create_text(10,450,text=text2,fill="yellow",font=myFont)
c.create_text(750,10,text=text3,fill="yellow",font=myFont)
c.create_text(750,450,text=text4,fill="yellow",font=myFont)
c.pack()
def update():
sensor = Adafruit_DHT.DHT22
DHT22_pin1 = 4
DHT22_pin2 = 17
DHT22_pin3 = 27
DHT22_pin4 = 22
humidity1, temperature1 = Adafruit_DHT.read_retry(sensor, DHT22_pin1)
humidity2, temperature2 = Adafruit_DHT.read_retry(sensor, DHT22_pin2)
humidity3, temperature3 = Adafruit_DHT.read_retry(sensor, DHT22_pin3)
humidity4, temperature4 = Adafruit_DHT.read_retry(sensor, DHT22_pin4)
text="Temperature1={0:0.1f}*C Humidity1={1:0.1f}%".format(temperature1, humidity1)
text="Temperature2={0:0.1f}*C Humidity2={1:0.1f}%".format(temperature2, humidity2)
text="Temperature3={0:0.1f}*C Humidity3={1:0.1f}%".format(temperature3, humidity3)
text="Temperature4={0:0.1f}*C Humidity4={1:0.1f}%".format(temperature4, humidity4)
window.after(100, update)
main()
update()
window.mainloop()
For some reason, my image is displaying as a blank gray background and my text is not displaying the readings or updating. instead I get this
What am I doing wrong, can anyone please explain what is going wrong here and how I might fix it?
With advice from some of the comments, I produced this, It works well. Thanks guys
from tkinter import *
from PIL import ImageTk
import Adafruit_DHT
import tkinter as tk
from tkinter import font as tkfont
sensor = Adafruit_DHT.DHT22
DHT22_pin1 = 4
DHT22_pin2 = 17
DHT22_pin3 = 27
DHT22_pin4 = 22
window = Tk()
c = Canvas(window,height=480,width=800)
image = ImageTk.PhotoImage(file="/home/pi/Desktop/AppFiles/AppBackround.jpg")
c.create_image(0,0,image=image,anchor=NW)
myFont = tkfont.Font(family="Titillium Web", size=32)
textVar1 = tk.StringVar()
textVar2 = tk.StringVar()
textVar3 = tk.StringVar()
textVar4 = tk.StringVar()
humidity1, temperature1 = Adafruit_DHT.read_retry(sensor, DHT22_pin1)
humidity2, temperature2 = Adafruit_DHT.read_retry(sensor, DHT22_pin2)
humidity3, temperature3 = Adafruit_DHT.read_retry(sensor, DHT22_pin3)
humidity4, temperature4 = Adafruit_DHT.read_retry(sensor, DHT22_pin4)
textVar1.set("Temperature1={0:0.1f}*C Humidity1={1:0.1f}%".format(temperature1, humidity1))
textVar2.set("Temperature2={0:0.1f}*C Humidity2={1:0.1f}%".format(temperature2, humidity2))
textVar3.set("Temperature3={0:0.1f}*C Humidity2={1:0.1f}%".format(temperature3, humidity3))
textVar4.set("Temperature4={0:0.1f}*C Humidity2={1:0.1f}%".format(temperature4, humidity4))
text1 = c.create_text(10,10,text=textVar1.get(),fill="yellow",font=myFont)
text2 = c.create_text(10,450,text=textVar2.get(),fill="yellow",font=myFont)
text3 = c.create_text(750,10,text=textVar3.get(),fill="yellow",font=myFont)
text4 = c.create_text(750,450,text=textVar4.get(),fill="yellow",font=myFont)
c.pack()
def update():
humidity1, temperature1 = Adafruit_DHT.read_retry(sensor, DHT22_pin1)
humidity2, temperature2 = Adafruit_DHT.read_retry(sensor, DHT22_pin2)
humidity3, temperature3 = Adafruit_DHT.read_retry(sensor, DHT22_pin3)
humidity4, temperature4 = Adafruit_DHT.read_retry(sensor, DHT22_pin4)
textVar1.set("Temperature1={0:0.1f}*C Humidity1={1:0.1f}%".format(temperature1, humidity1))
textVar2.set("Temperature2={0:0.1f}*C Humidity2={1:0.1f}%".format(temperature2, humidity2))
textVar3.set("Temperature3={0:0.1f}*C Humidity2={1:0.1f}%".format(temperature3, humidity3))
textVar4.set("Temperature4={0:0.1f}*C Humidity2={1:0.1f}%".format(temperature4, humidity4))
c.itemconfigure(text1, text=textVar1.get())
c.itemconfigure(text2, text=textVar2.get())
c.itemconfigure(text3, text=textVar3.get())
c.itemconfigure(text4, text=textVar4.get())
window.after(100, update)
update()
window.mainloop()

How to update Tkinter Progressbar?

So I'm writing some code to check VAT-IDs using a web API. Since some files have quite a large amount of API-calls it sometimes takes quite a while to complete and I want to show a progressbar so other users know that the program hasn't crashed yet. I found an example and modified it slightly so that it fits my needs. This code shows a window with a progressbar and once the for loop is finished the window closes.
import tkinter as tk
from tkinter import ttk
import time
def wrap():
MAX = 30000
root = tk.Tk()
root.geometry('{}x{}'.format(400, 100))
progress_var = tk.IntVar() #here you have ints but when calc. %'s usually floats
theLabel = tk.Label(root, text="Sample text to show")
theLabel.pack()
progressbar = ttk.Progressbar(root, variable=progress_var, maximum=MAX)
progressbar.pack(fill=tk.X, expand=1)
def loop_function():
k = 0
for k in range(MAX):
### some work to be done
progress_var.set(k)
time.sleep(0.002)
root.update()
root.destroy()
root.after(100, loop_function)
root.mainloop()
wrap()
Now I wanted to implement this into my tool:
import pandas as pd
import re
import pyvat
from tkinter import ttk
import tkinter as tk
def vatchecker(dataframe):
#initialise progressbar
root = tk.Tk()
root.geometry('{}x{}'.format(400, 100))
progress_var = tk.DoubleVar() #here you have ints but when calc. %'s usually floats
theLabel = tk.Label(root, text="Calling VAT Api")
theLabel.pack()
maxval = len(dataframe['Vat-ID'])
progressbar = ttk.Progressbar(root, variable=progress_var, maximum=maxval)
progressbar.pack(fill=tk.X, expand=1)
checked =[]
def loop_function():
for row in range(len(dataframe['Vat-ID'])):
print("Vatcheck: " + str(round(row/maxval * 100, 2)) + " %")
if pd.isna(dataframe['Vat-ID'][row]):
checked.append('No Vat Number')
else:
#check if vat id contains country code
groups = re.match(r'[A-Z][A-Z]', dataframe['Vat-ID'][row])
if groups != None:
querystring = dataframe['Vat-ID'][row][:-2]
country = dataframe['Vat-ID'][row][-2:]
#else get VAT-ID from Country ISO
else:
querystring = dataframe['Vat-ID'][row]
country = dataframe['Land-ISO2'][row]
try:
result = pyvat.check_vat_number(str(querystring), str(country))
checked.append(result.is_valid)
except:
checked.append('Query Error')
progress_var.set(row)
root.update()
root.destroy()
root.quit()
root.after(100, loop_function)
root.mainloop()
dataframe['Vat-ID-check'] = checked
return dataframe
This function gets called by the main script. Here the progressbar window is shown yet the bar doesn't fill up.
With print("Vatcheck: " + str(round(row/maxval * 100, 2)) + " %") I can still track the progress but it's slightly ugly.
Earlier in the main script the user already interacts with a Tkinter GUI but afterwards I close those windows and loops with root.destroy()' and 'root.quit() so I think it should be fine to run another Tkinter instance like this?
Any help or hints would be greatly appreciated.
as #jasonharper mentioned above changing progress_var = tk.DoubleVar() to progress_var = tk.DoubleVar(root) works

Looping in Tkinter isnt working as I intended

I am trying to update some buttons at the for loop in the end, which buttons I don't want to create individually.
I tried using:
While True:
root.update()
and the other type of update and also each one individually but no luck.
This is the code:
from tkinter import *
from tkinter.ttk import *
from PIL import Image
from functools import partial
import random
#define variables
#main_window_width = 500
#main_window_height = 500
#def functions
buttons_list = []
def InitButtons(n, k):
if k == 0:
k = n
for i in range(n):
InitButtons_column = i
if i//k > 0:
InitButtons_column = i%k
buttons_list.append(Label(main_window, image=button_img))
buttons_list[i].grid(row=(i//k), column=InitButtons_column)
def Hovering(e):
button_img = PhotoImage(file = '/home/klet/Desktop/projects/Python/GUI/button2.png')
buttons_list_button.config(image = button_img)
buttons_list_button.image = button_img
def Clicking(e):
button_img = PhotoImage(file = '/home/klet/Desktop/projects/Python/GUI/button3.png')
buttons_list_button.config(image = button_img)
buttons_list_button.image = button_img
def NotHovering(e):
button_img = PhotoImage(file = '/home/klet/Desktop/projects/Python/GUI/button1.png')
buttons_list_button.config(image = button_img)
buttons_list_button.image = button_img
def UpdatingButtons(n):
n.bind("<Enter>", Hovering)
n.bind("<Leave>", NotHovering)
n.bind("<Button-1>", Clicking)
n.bind("<ButtonRelease-1>", Hovering)
root = Tk()
button_img = PhotoImage(file = "/home/klet/Desktop/projects/Python/GUI/button1.png")
main_window = Frame(root)
main_window.place(relx=0.1, rely=0.1, relwidth=0.8, relheight=0.8)
InitButtons(10, 5)
#buttons_list_tmp1 = 0
#buttons_list_tmp1 += 1
#buttons_list_button =
#UpdatingButtons(buttons_list_tmp1)
#print(buttons_list_tmp1)
for i in range(len(buttons_list)):
buttons_list_button = buttons_list[i]
UpdatingButtons(buttons_list_button)
print(i)
root.mainloop()
The for loop above is only repeating once and i want it to be constantly updating, I also tried putting the whole code (within root and root.mainloop()) in a while loop but didnt work. I also searched some questions asked but they didnt seem to help.
I want to update the buttons(labels in this case) when I enter the button and when i click. Heres an example of what currently happening:
Link to vid
I made this account just to ask this question because I really dont like asking questions.

Make a reminder which will remind every X minute using Tkinter

I am totally new in python GUI and Tkinter. Now i want an entry field where i can change the value or time of self.hide when i will execute this code. that means self.hide value will change from Entry field. In this code this value is statically set to 1 minute. need help from experts.
import Tkinter as Tk
import time
import tkMessageBox
class Window:
def __init__(self):
self.root = None
self.hide = 1 #minutes
self.show = 3 #seconds
def close(self):
self.root.destroy()
return
def new(self):
self.root = Tk.Tk()
self.root.overrideredirect(True)
self.root.geometry("{0}x{1}+0+0".format(self.root.winfo_screenwidth(), self.root.winfo_screenheight()))
self.root.configure(bg='black')
Tk.Label(self.root, text='Hello', fg='white', bg='black', font=('Helvetica', 30)).place(anchor='center', relx=0.5, rely=0.5)
#tkMessageBox.showinfo("Notification", "Your time is up. Time to do next job. . .")
Tk.Button(text = 'Close', command = self.close).pack()
self.root.after(self.show*1000, self.pp)
def pp(self):
if self.root:
self.root.destroy()
time.sleep(self.hide*60)
self.new()
self.root.mainloop()
return
Window().pp()
Try This. It may help you.
from Tkinter import *
import time
root = Tk()
def close():
root.destroy()
def show():
root.deiconify()
button.config(text = 'Close', command = close)
root.after(1000, hide)
def hide():
root.withdraw()
time_to_sleep = set_time_to_sleep.get()
time_to_sleep = float(time_to_sleep)
#print time_to_sleep
time.sleep(time_to_sleep)
show()
set_time_to_sleep = Entry(root)
set_time_to_sleep.pack(side=LEFT)
button = Button(text = 'Set Time', command = hide)
button.pack()
root.mainloop()
To summarise:
Instead of using the sleep function, use the after function. This will not freeze the GUI.
Set the "wait" time of the after function self.Entry.get(). This will collect the info you have put into the Entry.
For more info, look at these links. People smarter than myself give a very clear explication on how to use the functions.
Tkinter, executing functions over time
tkinter: how to use after method

2nd Page not showing up?

This is my code :
import sys
from tkinter import *
#first new screen
def next_screen(names):
for widget in names:
widget.place_forget()
buttonhyp = Button (text = "button1",fg = "blue",command = hypoténusegetdef())
buttonhyp.grid (row = 1,column = 2)
def forget_page1():
widgets = [mLabel1, button]
next_screen(widgets)
################################################################################
def hypténusegetdef ():
widgets1 = [buttonhyp]
nextscreen1(widgets1)
def next_screen(names):
for widget in names:
widget.place_forget()
hyplabel1 = Label (text = "This is my text")
#first page things
mGui = Tk ()
mGui.geometry("600x600+545+170")
mGui.title("MyMathDictionary")
mLabel1 = Label (text = "Welcome to MyMathDictionary. Press Next to continue.",
fg = "blue",bg = "white")
mLabel1.place (x= 150,y = 200)
button = Button (text = "Next", command = forget_page1 )
button.place(x = 275,y = 230)
mGui.mainloop()
What i'm trying to do is to open the program and get the user to click on "Next" and then to show another button which is called "button1" and when the user clicks on "button1" it shows up a text called which says "This is my text" in my code.But when i run it i click on "Next" and nothing shows up i checked and re- checked but nothing seems to work.Any help would be appreciated.
#
I am not an expert, but i will give it a try.
Firstly, import sys is not necessary. And importing all the objects from tkinter module using from tkinter import* is not recommended. You should use import tkinter or import tkinter as tk to avoid unexepcted consequences.
You have 2 functions with the same name. next_screen(names) which should not happen.
Instead of using widgets = [mLabel1, button] to hide the widgets, you should put them in a frame so that you can use winfo_children() to find all the children widgets.
You should put the parent widget name when you create buttons and labels. for example,
import tkinter as tk
root = tk.Tk()
mylabel = tk.Label(root,text='this is a label')
mylabel.pack()
root.mainloop()
In your first next_screen(names) function , you used grid method to display the button. You should not mix the grid method and place method.
This is something i came up with
import tkinter as tk
def Screen_1():
Clear(myframe)
mybutton2= tk.Button(myframe,text = "Button1", command = Screen_2)
mybutton2.pack()
def Screen_2():
Clear(myframe)
mylabel2= tk.Label(myframe,text = "This is my text",fg = "blue",bg = "white")
mylabel2.pack(side='top')
def Clear(parent):
for widget in parent.winfo_children():
widget.pack_forget()
root =tk.Tk()
myframe=tk.Frame(root)
myframe.pack()
mylabel1= tk.Label(myframe,text = "Welcome to MyMathDictionary. Press Next to continue.",fg = "blue",bg = "white")
mylabel1.pack(side='top')
mybutton1= tk.Button(myframe,text = "Next", command = Screen_1)
mybutton1.pack(side='bottom')
root.mainloop()
hope it helps!

Categories

Resources