Close the message button - python-2.7

import os
import Tkinter
gui = Tkinter.Tk()
gui.geometry("300x200")
messagebutton1 = Tkinter.Button(gui,text='Process Completed')
messagebutton1.place(x=80,y=80)
This is my example.I need to close this "process Completed" message button by clicking.What is the syntax for that.can you please guide me.

Use destroy method to close Tk.
import os
import Tkinter
def close():
gui.destroy()
gui = Tkinter.Tk()
gui.geometry("300x200")
messagebutton1 = Tkinter.Button(gui,text='Process Completed', command=close)
messagebutton1.place(x=80,y=80)
gui.mainloop()

Related

Django - Whatsapp Sessions for scheduled messages

I'm developing a system where users, in addition to all the bureaucratic part, can register their clients' whatsapp so that automatic billing messages, congratulations, etc. are sent. Where the user would read the QR code and the system would be in charge of sending messages over time, using the user's whatsapp, thus opening a user<-> clinet conversation. I'm dividing this problem into parts, for now I'm trying to read the Whatsapp Web Qr Code and display it in a template. This is already happening. The problem is that the webdriver is terminated first, as soon as the image is returned to the template, then the session cannot be validated. The webdriver remains open forever, or closes before the image is sent to the template, the image needs to go to the template via return (or another way) and the webdriver remains active for a while. How to solve this concurrent task?
# views.py
from django.shortcuts import render
from django.http import HttpResponse
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import base64
import time
from django.shortcuts import render
def read_qr_code(request):
driver = webdriver.Firefox()
# driver.implicitly_wait(30) # mantém o webdriver ativo por 2 minutos
driver.get('https://web.whatsapp.com/')
wait = WebDriverWait(driver, 10)
qr_element = wait.until(EC.presence_of_element_located((By.XPATH, '//*[#id="app"]/div/div/div[3]/div[1]/div/div/div[2]/div/canvas')))
qr_image_binary = qr_element.screenshot_as_png
qr_image_base64 = base64.b64encode(qr_image_binary).decode('utf-8')
context = {
'image_data': qr_image_base64
}
# send_qr(request, context)
# time.sleep(20) # aguarda por 2 minutos
# driver.quit() # fecha o webdriver
return render(request, 'read_qr_code.html', context)
I solved this problmes using Threds, the code is.
# views.py
from django.shortcuts import render
from django.http import HttpResponse
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import base64
import time
from django.shortcuts import render
import threading
def quit_driver_thread():
time.sleep(40)
driver.quit()
def read_qr_code(request):
global driver
driver = webdriver.Firefox()
driver.implicitly_wait(120)
driver.get('https://web.whatsapp.com/')
wait = WebDriverWait(driver, 10)
qr_element = wait.until(EC.presence_of_element_located((By.XPATH, '//*[#id="app"]/div/div/div[3]/div[1]/div/div/div[2]/div/canvas')))
qr_image_binary = qr_element.screenshot_as_png
qr_image_base64 = base64.b64encode(qr_image_binary).decode('utf-8')
context = {
'image_data': qr_image_base64
}
thread = threading.Thread(target=quit_driver_thread)
thread.start()
return render(request, 'read_qr_code.html', context)

Running a Kivy screen inside a Pyqt app ,

I am trying to make a simple maths quiz game that shows Numbers and when I press space it shows the result , the Application launch with a QTdyalog GUI first and after I finish configuring the gameplay a Kivy screen should show up and the game starts until the user press escape it gets back to the config GUI
here is the Programm skeleton
import kivy
from kivy.app import App
from kivy.uix.label import Label
import sys
from PyQt4 import QtCore, QtGui, uic
qtCreatorFile = "ConfigForm.ui" # Enter file here.
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
class Playy(App): #the Kivy app
def build(self):
l = Label(text='Hello world')
return l
class Conf(QtGui.QDialog, Ui_MainWindow): #the COnfiguration Gui
def __init__(self):
QtGui.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
self.setupUi(self)
self.buttonBox.accepted.connect(self.oky)
self.buttonBox.rejected.connect(self.notok)
def oky(self):
print "OK OK OK OK" #creating a Kivy app instance and running it
ins = Playy()
ins.run()
def notok(self):
print "cancel cancel"
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = Conf()
window.show()
sys.exit(app.exec_())
I am only having Issue with making functions inside the Kivy app class and passing arguments Into them and also handling Objects properties such as label text this is my first Kivy experiment tell me what do you think

calling a python script on button click using python and tkinter

I have a python script which has the functionality of sending an email to a user. I executed this script and it is working fine. In another python script I have only a button, so when I click on this button I want the other python script which sends a email to be executed.I have written the following code:
#!/usr/bin/python
import sys
import os
import Tkinter
import tkMessageBox
top=Tkinter.Tk()
def helloCallBack():
os.system('SendEmail.py')
B=Tkinter.Button(top,text="hello",command= helloCallBack)
B.pack()
top.mainloop()
I get the following error when I click on the button:
sh: 1:SendEmail.py:not found.
Could you let me know what is the reason for this error and how it can be resolved.Thanks.
I was able to figure out a way to call another python script on button click:
instead of using os.system('SendEmail.py') we need to use os.system('python SendEmail.py')
import sys
import os
from tkinter import *
window=Tk()
window.title("Running Python Script")
window.geometry('550x200')
def run():
os.system('opencv_video.py')
btn = Button(window, text="Click Me", bg="black", fg="white",command=run)
btn.grid(column=0, row=0)
window.mainloop()
If your SendEmail.py is in the same location, use os.system('SendEmail.py'). If it's in a different location, use os.system('python SendEmail.py').
#!/usr/bin/python
import sys
import sys
import os
import Tkinter
import tkMessageBox
top=Tkinter.Tk()
def helloCallBack():
os.system('python SendEmail.py')
B=Tkinter.Button(top,text="hello",command= helloCallBack)
B.pack()
top.mainloop()
use the keyword "python" to run the command
As an amateur, I am not really qualified to give advice. This is how I did it.
I want to do this kind of thing too. I have about 16 little python programs which make html, sets of checkboxes, sets of radiobuttons, text input fields, html tables etc.
In another thread here a comment was quite deprecative of using os.system calls. Not sure why, but I thought I would try another approach.
I've just started learning tkinter, so I am making each of my 'makehtml' functions run in a window.
Now I want a master window with buttons. Click a button and another window opens, say the checkboxes window, or any of the other windows for making html.
I made a module: guiHTML.py All my 'makehtml' functions are in there.
Import guiHTML in the master window.
import os, sys
# to import the files we need the paths
path = '/home/pedro/myPython/myModules/'
# append the paths
sys.path.append(path)
import tkinter as tk
from functools import partial
import guiHTML
Then, in the master window make a function like this for each button:
def openCheckboxes():
#call the checkboxes function defined in the guiHTML module
guiHTML.checkboxes()
Then, in the checkboxes button just put this:
btn3 = tk.Button(frame1, text='insert checkboxes', command=openCheckboxes)
btn3.grid(columnspan=2, column=0, row=2, sticky='w', pady=10)
Click btn3 and the checkboxes window opens.
This works for me, but I don't know if it is a good way to do this. I only began with tkinter a month ago.
If there is a better way to do this, I'd be glad to hear it from you experts!
#!/usr/bin/python
import sys
import os
import tkinter as tk
root = tk.Tk()
def helloCallBack():
os.system('call.py')
#Keep_both_files_in_the_same_Folder
b1=tk.Button(root, text="Calendar",bg="white",command=helloCallBack)
b1.pack()
root.mainloop()

Embed a pyplot in a tkinter window and update it

I am trying to write a program that has a pyplot (as in matplotlib.pyplot) within a Tkinter GUI which can be updated. Basically what I want is a program with a Tkinter interface to be displaying some data on a pyplot, then when the program gets some new data I want to update the pyplot to contain the new data.
Here is a minimal example:
import numpy as np
import Tkinter as tk
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
root = tk.Tk()
fig = plt.figure(1)
t = np.arange(0.0,3.0,0.01)
s = np.sin(np.pi*t)
plt.plot(t,s)
canvas = FigureCanvasTkAgg(fig, master=root)
plot_widget = canvas.get_tk_widget()
def update():
s = np.cos(np.pi*t)
plt.plot(t,s)
plt.draw()
plot_widget.grid(row=0, column=0)
tk.Button(root,text="Update",command=update).grid(row=1, column=0)
root.mainloop()
What I expect to happen is, for a window to pop up with a plot containing a sine wave and a button. When I press the button a cosine wave should appear on the plot.
What actually happens when I run the program is that a window pops up with a plot containing a sine wave and a button. However when I press the button nothing happens. The plot does not seem to be updating.
I'm probably making some newbie mistake but I can't find any examples online of doing this sort of thing. What is going wrong here and how would I get what I want?
Any help would be greatly appreciated!
I figured it out, I need to call the draw() method on the figure's canvas attribute in order to get it to redraw, the corrected code is below. Also anyone who is encountering this or similar problems should probably look at matplotlib.animate if they need to be dynamically updating their pyplot
import numpy as np
import Tkinter as tk
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
root = tk.Tk()
fig = plt.figure(1)
plt.ion()
t = np.arange(0.0,3.0,0.01)
s = np.sin(np.pi*t)
plt.plot(t,s)
canvas = FigureCanvasTkAgg(fig, master=root)
plot_widget = canvas.get_tk_widget()
def update():
s = np.cos(np.pi*t)
plt.plot(t,s)
#d[0].set_ydata(s)
fig.canvas.draw()
plot_widget.grid(row=0, column=0)
tk.Button(root,text="Update",command=update).grid(row=1, column=0)
root.mainloop()

How to transfer value from one python script class to another python script

I need to connect two python script class to each other and transfer values.
It seems that I made some mistakes to initialize the class objects and passing the
values please note the way I followed and somebody please kindly advise me on where I am getting wrong.
what is wrong with this line of code
def TransferTreeVal(objSubS):
objCM=MainScript.clsMain()
print "Transfer value"
Some more detailed code
##MainScript.py
import os
from Tkinter import *
import Tkinter as tk
import ttk
class clsMain():
def __init__ (objCM):
root['width']=500
root['height']=400
root['bg']='brown'
objCM.MethodDisplay()
def MethodDisplay(objCM):
print "display windows"
root=tk.Tk()
objCM = clsMain()
root.mainloop()
##SubScript.py
import os
from Tkinter import *
import Tkinter as tk
import ttk
import MainScript
class clsSubS():
def __init__ (objSubS):
root['width']=500
root['height']=500
root['bg']='brown'
objSubS.DispWin()
def TransferTreeVal(objSubS):
objCM=MainScript.clsMain()
print "Transfer value"
root=tk.Tk()
objSubS = clsSubS()
The main thing you are doing wrong is that you are importing files that have executable code in them. When you import SubScript.py, it is going to execute the code at the bottom which creates an instance of Tk. However, your main script also creates an instance of Tk and you should only ever have a single instance in a running program.
Normally, if you have a class you want to import, but you also want to use it as a standalone script, you "hide" the standalone script code behind a check like this:
if __name__ == "__main__":
root = tk.Tk()
objSubS = clsSubS()
With that, the code will only get executed if you do python SubScript.py. Also, when you import SubScript, that code will not run.