Python Tkinter: destroy() my Toplevel() window - python-2.7

I don't understand what I'm doing wrong.
I'm trying to create a log in window. When you click Log in, I want to to go do stuff and after that close out and go to the main GUI.
I found a bunch of stuff online that I can't make heads or tails of. I do not want to cut and paste other people's code which I do not fully understand.
So I'd like to understand what I'm doing wrong here. To start I created a destroyWindow() method which I call from the button as just a starting point.
There is a scope issue where loginWindow does not exist within its own class. I thought the class application would get around the scope issue. I tried using 'self.' but to no avail. I tried random things I saw in other people's code. Please can someone pinpoint what I'm missing here? I get
NameError: global name 'loginWindow' is not defined
#!/Usr/bin/Python
import Tkinter,tkFileDialog,tkMessageBox
from Tkinter import *
from tkFileDialog import *
import sys, time, datetime
import pathlib
from pathlib import * #makes it really easy to travers folders if needed.
mainWindow = Tk()
mainWindow.wm_title("my prog")
mainWindow.wm_iconbitmap('fb_logo_sm.ico')
mainFrame = Frame(mainWindow)
mainFrame.grid(padx=10,pady=10)
class loginWindowClass():
def __init__(self):
loginWindow = Tkinter.Toplevel()
loginWindow.configure(bg='#22BEF2')
loginWindowFrame = Frame(loginWindow,bg='#22BEF2')
loginWindowFrame.grid(padx=90,pady=50)
loginWindow.wm_title("log in")
loginWindow.wm_iconbitmap('my.ico')
usernameLable = Tkinter.Label(loginWindowFrame,text="User Name",fg='#FFFFFF',bg='#22BEF2')
usernameLable.grid(row=1,column=2,padx=(0,5),sticky=W+S)
usernameField = Entry(loginWindowFrame)
usernameField.config(width=24)
usernameField.grid(row=2,column=2)
passwordLable =Tkinter.Label(loginWindowFrame,text="Password",fg='#FFFFFF',bg='#22BEF2')
passwordLable.grid(row=3,column=2,sticky=W+S)
passwordField = Entry(loginWindowFrame)
passwordField.config(width=24)
passwordField.grid(row=4,column=2)
loginButton = Button(loginWindowFrame, text='Log In', height=1, width=20, wraplength=100, fg='white',bg='#bbbbbb',command=self.destroyWindow).grid(row=5,column=2,pady=(10,0))
def destroyWindow(self):
loginWindow.destroy()
logwin = loginWindowClass()
mainWindow.mainloop()

Ah. 'self.' is the answer indeed.
I did not apply it everywhere. Here is the solution
#!/Usr/bin/Python
import Tkinter,tkFileDialog,tkMessageBox
from Tkinter import *
from tkFileDialog import *
import sys, time, datetime
import pathlib
from pathlib import * #makes it really easy to travers folders if needed.
mainWindow = Tk()
mainWindow.wm_title("my prog")
mainWindow.wm_iconbitmap('fb_logo_sm.ico')
mainFrame = Frame(mainWindow)
mainFrame.grid(padx=10,pady=10)
class loginWindowClass():
def __init__(self):
self.loginWindow = Tkinter.Toplevel()
self.loginWindow.configure(bg='#22BEF2')
loginWindowFrame = Frame(self.loginWindow,bg='#22BEF2')
loginWindowFrame.grid(padx=90,pady=50)
self.loginWindow.wm_title("log in")
self.loginWindow.wm_iconbitmap('my.ico')
usernameLable = Tkinter.Label(loginWindowFrame,text="User Name",fg='#FFFFFF',bg='#22BEF2')
usernameLable.grid(row=1,column=2,padx=(0,5),sticky=W+S)
usernameField = Entry(loginWindowFrame)
usernameField.config(width=24)
usernameField.grid(row=2,column=2)
passwordLable =Tkinter.Label(loginWindowFrame,text="Password",fg='#FFFFFF',bg='#22BEF2')
passwordLable.grid(row=3,column=2,sticky=W+S)
passwordField = Entry(loginWindowFrame)
passwordField.config(width=24)
passwordField.grid(row=4,column=2)
loginButton = Button(loginWindowFrame, text='Log In', height=1, width=20, wraplength=100, fg='white',bg='#bbbbbb',command=self.destroyWindow).grid(row=5,column=2,pady=(10,0))
def destroyWindow(self):
self.loginWindow.destroy()
logwin = loginWindowClass()
mainWindow.mainloop()

Related

PyQt :Parent Window not waiting until child window closes.

PyQt :Parent Window not waiting until child window closes. with reference to code shared below ,My welcome class object should wait till first_time class object completely finishes executing , but instead goes ahead and closes it self before first_time object finishes executing .
code :
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PySide.QtCore import QSettings
import sys
from PyQt4 import uic
#importing first configuration class
import configure as config_first
#loading initial settings
settings=QSettings('settings.ini',QSettings.IniFormat)
#loading the ui screens
form_class=uic.loadUiType("screens/firstscreen.ui")[0]
class welcome(QDialog,form_class):
#this signal is emitted when first configuration is done and ready to go
done_and_go_to_use = pyqtSignal()
def __init__(self):
super(welcome, self).__init__()
self.setupUi(self)
self.done_and_go_to_use.connect(self.close)
self.ready_btn.clicked.connect(self.ready)
def ready(self):
if_configured = settings.value('isConfigured', False)
if not if_configured :
first_time=config_first.configureFirst(self)
first_time.show()
self.close()
app = QApplication(sys.argv)
p = welcome()
p.show()
app.exec_()
below is the code for configure.py
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sqlite3
import csv
from PySide.QtCore import QSettings
from PyQt4 import uic
#loading initial settings
settings=QSettings('settings.ini',QSettings.IniFormat)
#loading ui screens
form_class=uic.loadUiType("screens/config_first.ui")[0]
#database connecting
con = sqlite3.connect("local.db")
cur = con.cursor()
cur.execute("CREATE TABLE if not exists marks (student_id int,student_name varchar(200));")
class configureFirst(QDialog,form_class):
done_configuring=pyqtSignal()
try_again=pyqtSignal()
def __init__(self,parent=None):
super(configureFirst, self).__init__(parent)
self.setupUi(self)
self.ok_btn.clicked.connect(self.ok_clicked)
self.cancel_btn.clicked.connect(self.cancel_clicked)
self.try_again.connect(self.ok_clicked)
self.done_configuring.connect(self.cancel_clicked)
self.show()
def ok_clicked(self):
file_select=QFileDialog.getOpenFileName(self,"open file","/")
if file_select:
with open(file_select, 'rb') as f:
reader = csv.reader(f)
ed = list(reader)
for row in ed:
if "name" not in row or "id" not in row:
cur.execute("Insert into marks Values (?,?);",(row[0],row[1]))
con.commit()
settings.setValue("isConfigured",True)
self.done_configuring.emit()
else:
#if recurssion is used the no of time it has to close increases and leads to integration problems
self.try_again.emit()
def cancel_clicked(self):
if_configured=settings.value("isConfigured")
if if_configured:
self.close()
else:
QMessageBox.critical(self,"PerfAnalyser","You Need to Configure For PerfAnalyser To Work")
def closeEvent(self,event):
#this method is triggered when 'X' is clicked i.e close button is clicked at the upper right corner
if_configured = settings.value("isConfigured")
if if_configured:
event.accept()
else:
QMessageBox.critical(self, "PerfAnalyser", "You Need to Configure For PerfAnalyser To Work")
event.ignore()
Thanks for the help in advance ...
I will try to help out since I notice few people have seen your post. I have had this happen a long time ago so I need a reminder, but I was unable to get your code running, I also tried to recreate your ui files and the screens directory but I was not successful. However, maybe the following is still useful.
In my working code, any time I needed to create a subwindow, I executed subwindows as follows from the main window's module:
dlg = SubWindowModuleName.StartSub()
dlg.exec_()
This will execute the subwindow and waits for it to close. Then, on the subwindow module (SubWindowModuleName in the above code, "configure" for you), I did this:
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(982, 521)
... # here I build the window (I noticed that you import UI files which is a much better way of doing this)
...
class StartSub(QtGui.QDialog, Ui_Dialog):
def __init__(self,parent=None):
QtGui.QDialog.__init__(self,parent)
self.setupUi(self)

Python+Glade Set Label text

I have a little python script with a Gladefile but my code i not doing was i wanted it to.
There several issues that i can't solve. Just trying to get a date/time written on my label "DK_Tid".
But I get an error:
self.DK_Tid.set_text(dk_time)
NameError: global name 'self' is not defined
And when i have tried to move the thread out of class, there is no print, but window is showed. All sort of variation i've tried, but now i'm stuck.
No mather what i do, it won't work.
Can anyone help me?
#!/usr/bin/env python
#
# Time test deppends on test.glade
import sys, time, thread, gi
gi.require_version('Gtk', '3.0')
from gi.repository import GObject,Gtk as Gtk
gi.require_version('GdkX11', '3.0')
from gi.repository import GdkX11
from datetime import datetime, timedelta
class GTK_Main(object):
def __init__(self):
self.gladefile = ("test.glade")
self.builder = Gtk.Builder()
self.builder.add_from_file(self.gladefile)
self.builder.connect_signals(self)
## Create objects by name from glade
self.window = self.builder.get_object("window")
self.DK_Tid = builder.get_object("DK_Tid")
self.window.show_all()
# Create handles
def on_window_destroy(self, object, data=None):
Gtk.main_quit()
def UTC_time():
now = datetime.now()
new_time = now + timedelta(hours=0, minutes=0, seconds=1)
while True:
if new_time < datetime.now():
dk_time = time.strftime("%d %B %Y %H:%M:%S")
self.DK_Tid.set_text(dk_time)
print dk_time
now = new_time
new_time = now + timedelta(hours=0, minutes=0, seconds=1)
thread.start_new_thread(UTC_time())
GObject.threads_init()
GTK_Main()
Gtk.main()
Solution found by myself. :-)
Gtk is strange sometimes.
I think that i needed to put in after the if function:
while Gtk.events_pending():
Gtk.main_iteration()
But is quite some time ago i made that script.

How to put dates on the x qwtplot axis in python?

I visited tons of pages in the internet but only have examples in C and I dont understand how to make this in python. Can someone helpme.
I use Pyqt designer and Python 2.7. I need plot data whith dates on a GUI using qwtplot.
you need a QwtScaleDraw class e.g.:
class TimeScaleDraw(QwtScaleDraw):
def __init__(self, baseTime, *args):
QwtScaleDraw.__init__(self, *args)
self.baseTime = baseTime
def label(self, value):
upTime = self.baseTime.addSecs(int(value))
return QwtText(upTime.toString())
then you modify your x axis with this code:
self.setAxisScaleDraw(
QwtPlot.xBottom, TimeScaleDraw(self.cpuStat.upTime()))
where self's base class is QwtPlot. cpuStat.upTime() returns a QTime instance. value represents one of your time data points. This code is from the cpuDemo example code.
To get this example cpuDemo working with python xy 2.7. make these changes to the imported modules:
import os
import sys
import numpy as np
from PyQt4.QtGui import (QApplication, QColor, QBrush, QWidget, QVBoxLayout,
QLabel)
from PyQt4.QtCore import QRect, QTime
from PyQt4.QtCore import Qt
from PyQt4.Qwt5 import (QwtPlot, QwtPlotMarker, QwtScaleDraw, QwtLegend, QwtPlotCurve,
QwtPlotItem, QwtText)#, QwtLegendData
then comment out all legend lines.
I adopted this code to use the QDateTime class. Here is a snippet:
from PyQt4 import QtCore, QtGui, Qt
from PyQt4 import Qwt5
class TimeScaleDraw(Qwt5.QwtScaleDraw):
def __init__(self, *args):
Qwt5.QwtScaleDraw.__init__(self,unixBaseTime *args)
self.basetime=unixBaseTime
self.fmt='h:mm\nd-MMM-yyyy'
def label(self, value):
dt = QtCore.QDateTime.fromMSecsSinceEpoch((value+self.basetime))
return Qwt5.QwtText(dt.toString(self.fmt))
...
class Ui_TabWidget(object):
def setupUi(self, TabWidget):
self.qwtPlot = Qwt5.QwtPlot()
self.qwtPlot.setAxisScaleDraw(Qwt5.QwtPlot.xBottom, TimeScaleDraw(unixBaseTime))
admire pretty picture

how to display a form within a frame using python and tkinter

I have created a notebook(file1.py) using python and tkinter. This notebook has three tabs A,B,C. I have another python file(file2.py) which contains few text fields. Now I am looking for a way to display the contents of the other file2.py within the tab A which is in file1.py.The following is the code I used in file1.py
import tkinter as tk
import tkinter.ttk as ttk
root = tk.Tk()
# use width x height + x_offset + y_offset (no spaces!)
root.geometry("%dx%d+%d+%d" % (300, 200, 100, 50))
root.title('test the ttk.Notebook')
nb = ttk.Notebook(root)
nb.pack(fill='both', expand='yes')
# create a child frame for each page
f1 = tk.Frame(bg='red')
f2 = tk.Frame(bg='blue')
f3 = tk.Frame(bg='green')
# create the pages
nb.add(f1, text='A')
nb.add(f2, text='B')
nb.add(f3, text='C')
# put a button widget on child frame f1 on page1
btn1 = tk.Button(f1, text='button1')
btn1.pack(side='left', anchor='nw', padx=3, pady=5)
root.mainloop()
File2.py
import sys
from PyQt4 import Qt
from taurus.qt.qtgui.application import TaurusApplication
app = TaurusApplication(sys.argv)
panel = Qt.QWidget()
layout = Qt.QHBoxLayout()
panel.setLayout(layout)
from taurus.qt.qtgui.panel import TaurusForm
panel = TaurusForm()
model = [ 'test/i1/1/%s' % p for p in props ]
panel.setModel(model)
panel.show()
sys.exit(app.exec_())
I am new to using tkinter and python so could you let me know how I could achieve it. Also in the other file(file2.py) I have few import statements like 'import sys" etc.Thanks.
You cannot mix those two files. One uses Tkinter, one uses PyQT. Those two libraries are incompatible with each other.

SVG rendering differs between Safari/Chrome/Firefox

I am dynamically generating a figure as part of a website. The figure is generated by matplotlib as part of a Django view function. Within the view function, I render the figure as an SVG and then add that SVG's content to the view's context and then render a very simple template using that context. It's a graph of temperature over time from a particular sensor.
When I view the page in a browser, everything works right, in general terms: the graph is shown in the right place and generally shows the right info. But the image looks different when viewed in Safari vs either Chrome or Firefox.
Here's how it looks in Chrome/Firefox:
And here's how it looks in Safari:
A link to the SVG itself is here.
Here's the code that is generating the SVG:
from django.views.generic import TemplateView
from mysite.models import TempReading, TempSeries
import numpy as np
import pandas as pd
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import seaborn as sbn
import StringIO
class TestView(TemplateView):
template_name = 'mysite/test.html'
def get_context_data(self, **kwargs):
upstairs = TempSeries.objects.get(name='Upstairs')
upstairstemps = upstairs.tempreading_set.all().order_by('-timestamp')
frame = pd.DataFrame(list(upstairstemps.values()))
frame.set_index('timestamp', inplace=True)
fig = Figure()
ax = fig.add_subplot(1,1,1)
frame['value'].plot(ax=ax)
ax.get_xaxis().grid(color='w', linewidth=1)
ax.get_yaxis().grid(color='w', linewidth=1)
fig.set(facecolor='w')
canvas = FigureCanvas(fig)
imgdata = StringIO.StringIO()
canvas.print_svg(imgdata)
imgstr = imgdata.getvalue()
context = super(TestView, self).get_context_data(**kwargs)
context['svgtext'] = imgstr
return context
Any thoughts on why the SVG would render differently in different browsers?