WxPython Pango error after clicking on wx.SpinCtrl - wxwidgets

The actual error is produced by a much larger program I've been writing, but the following sample reproduces the error:
import wx
class MyLine(wx.Frame):
def __init__(self):
self.thickness = 1
self.length = 10
self.spin_ctrl = []
super(MyLine, self).__init__(None)
self.SetBackgroundColour(wx.ColourDatabase().Find("GREY"))
vbox = wx.BoxSizer(wx.VERTICAL)
#Length section
self.spin_ctrl.append(wx.SpinCtrl(self, initial = self.length, min = 1, max = 100))
vbox.Add(self.spin_ctrl[-1], 0, wx.ALL | wx.ALIGN_CENTER, 5)
#Thickness section
self.spin_ctrl.append(wx.SpinCtrl(self, initial = self.thickness, min = 1, max = 10))
vbox.Add(self.spin_ctrl[-1], 0, wx.ALL | wx.ALIGN_CENTER, 5)
self.SetSizerAndFit(vbox)
self.Show()
app = wx.App()
fr = MyLine()
app.MainLoop()
When the above is run, a window appears with two SpinCtrl buttons. If I click on the first one to change the value and then close the window, everything works fine and there are no error messages. When I click on the second button to change its value and then close the window, the following error appears:
Pango-CRITICAL **: pango_layout_get_cursor_pos: assertion 'index >= 0 && index <= layout->length' failed. Is this a bug or am I not using SpinCtrl buttons correctly?
I am running WxPython4.0.3.

Related

How to Screenshot a Website Element without Collapsible Division using Selenium?

I want to screenshot just the US hot pots map in https://www.nytimes.com/interactive/2021/us/covid-cases.html but the collapsible division at the very bottom (that says Thanks for reading the Times) keeps coming with the screenshot:
How can I exclude that?
Also ideally the New York Time banner at the top would be cropped out. I used Pillow's Image.crop() to crop from the first image captured but wonder if there is a more convenient/elegant way to achieve that. Any thoughts? Thank you!
Here's my code:
from Screenshot import Screenshot
from selenium.webdriver.common.by import By
from selenium import webdriver
from PIL import Image
ob = Screenshot.Screenshot()
driver = webdriver.Chrome()
driver.page_load_strategy = 'none'
url = "https://www.nytimes.com/interactive/2021/us/covid-cases.html"
driver.get(url)
class_name = "mapboxgl-canvas"
element = driver.find_element(By.CLASS_NAME, class_name)
element.screenshot('{}.png'.format(class_name))
location = element.location
size = element.size
print(class_name, 'location:', location, 'size:', size, '\n')
location = element.location
size = element.size
x = location['x']
# y = location['y']
y = 30
w = x + size['width']
h = y + size['height']
# x = 0; y = 10; w = 950; h = 600
fullImg = Image.open("mapboxgl-canvas.png")
cropImg = fullImg.crop((x, y, w, h))
cropImg.save('cropImage.png')
driver.close()
driver.quit()
After tons of trials and errors, finally I got my code to work. The key is to suppress the expandable dock and re-position the capturing window in js.
Attached is the map with top banner and bottom mapbox logo cropped out.
import platform
from Screenshot import Screenshot
from selenium.webdriver.common.by import By
from PIL import Image, ImageDraw
from selenium import webdriver
from selenium.webdriver import ChromeOptions
import numpy as np
#-------------------------------- Part 1 Take a Screenshot of the Map -----------------------------------
#Set up Chrome driver
options = ChromeOptions()
options.headless = True
options.add_argument('--page_load_strategy = none') #suppress browser window
driver = webdriver.Chrome(executable_path = ('/usr/local/bin/' if platform.system() == 'Linux' else '' + 'chromedriver')
, options=options)
# driver.get_window_rect()
_ = driver.set_window_rect(x=0, y=50, width=1000, height=1000)
# driver.execute_script("document.body.style.zoom='145%'")
#Load the website to capture screenshot
url = "https://www.nytimes.com/interactive/2021/us/covid-cases.html"
driver.get(url)
driver.execute_script("""window.scrollTo(0, 2071);
var element = document.querySelector('[data-testid="expanded-dock"]');
element.style.visibility = 'collapse';
element.style.height = '0px';""") #Suppress the randomly pop-out expandable dock at the bottom which messes up the screenshot window
#Identify the element to screenshot, which is the hot spots map
#-------------------------------------------------------------------------------------------------------
#Can't use class_name = "mapboxgl-canary",'multi-map', "map-wrap", "mapboxgl-interactive"
#These class_names are the same as "mapboxgl-canvas": "aspect-ratio-outer", "aspect-ratio-inner", "map", "mapboxgl-map"
#Using ID = "maps" works too, just y location is different. Stick to class_name = "mapboxgl-canvas"
# tag = "maps"
# element = driver.find_element(By.ID, tag)
#-------------------------------------------------------------------------------------------------------
tag = "mapboxgl-canvas"
element = driver.find_element(By.CLASS_NAME, tag)
img_path = '{}.png'.format(tag)
_ = element.screenshot(img_path)
#Check map location and size for window.scrollTo coordinates
location = element.location
size = element.size
print(tag, 'location:', location, 'size:', size, '\n')
# Make sure window.scrollTo = y location = 2382 and height and width stay at 643 and 919 when configuring set_window_rect()
# mapboxgl-canvas location: {'x': 30, 'y': 2382} size: {'height': 643, 'width': 919}
#Crop image to remove unwanted pixels
# x = location['x']
# y = location['y']
x=0; y=30 #Start from a lower position to crop the top banner
w = x + size['width']
h = y + size['height'] - 60 #Subtract from height to remove mapbox logo at the bottom
fullImg = Image.open(img_path)
cropImg = fullImg.crop((x, y, w, h)) #(left, upper, right, lower)-tuple
cropImg.save('cropImage.png')
fullImg.close()
driver.close()
driver.quit()
#--------- Part 2 Mask unwanted parts of the image (top right size control, P.R. region at bottom right) -----------
im = Image.open('cropImage.png')
draw = ImageDraw.Draw(im)
#Vertices of masking rectangles, one for top right size control, the other for bottom right Puerto Rico
top_left = (cropImg.width -41, 0)
bottom_right = (cropImg.width - 8, 40)
top_left2 = (cropImg.width - 100, cropImg.height - 45)
bottom_right2 = (cropImg.width - 40, cropImg.height - 15)
draw.rectangle((top_left, bottom_right), fill=(255, 255, 255))
draw.rectangle((top_left2, bottom_right2), fill=(255, 255, 255))
# Save final image
im.save('cropImage1.png')

pyqgis(pyqt5,QGIS3 plugin) mouse clicked popup and get the point x,y

I used this code in qgis2 plugin. But I cannot use in qgis3. The error code is no connect lib in QObject. How can I solve or change my code?
def handleMouseDown(self, point, button):
global coor_x, coor_y, width
width = round(self.iface.mapCanvas().mapUnitsPerPixel() * 2, 4)
coor_x = round(point.x(), 4)
coor_y = round(point.y(), 4)
self.dlg.show()
def run(self):
self.pointEmitter = QgsMapToolEmitPoint(self.iface.mapCanvas())
QObject.connect(self.pointEmitter, SIGNAL("canvasClicked(const QgsPoint, Qt::MouseButton)"), self.handleMouseDown)
self.iface.mapCanvas().setMapTool(self.pointEmitter)

Can this PyGame code run 60fps for >40 critters?

In my other question, some of the posters asked to see the code and suggested I make a new question. As requested, here is most of the code I'm using. I've removed the Vector class, simply because it's a lot of code. It's well-understood math that I got from someone else (https://gist.github.com/mcleonard/5351452), and cProfile didn't have much to say about any of the functions there. I've provided a link in the code, if you want to make this run-able.
This code should run, if you paste the the vector class where indicated in the code.
The problem is, once I get above 20 critters, the framerate drops rapidly from 60fps to 11fps around 50 critters.
Please excuse the spaghetti-code. Much of this is diagnostic kludging or pre-code that I intend to either remove, or turn into a behavior (instead of a hard-coded value).
This app is basically composed of 4 objects.
A Vector object provides abstracted vector operations.
A Heat Block is able to track it's own "heat" level, increase it and decrease it. It can also draw itself.
A Heat Map is composed of heat blocks which are tiled across the screen. When given coordinates, it can choose the block that those coordinates fall within.
A Critter has many features that make it able to wander around the screen, bump off of the walls and other critters, choose a new random direction, and die.
The main loop iterates through each critter in the "flock" and updates its "condition" (whether or not it's "dying"), its location, its orientation, and the heat block on which it is currently standing. The loop also iterates over each heat block to let it "cool down."
Then the main loop asks the heat map to draw itself, and then each critter in the flock to draw itself.
import pygame
from pygame import gfxdraw
import pygame.locals
import os
import math
import random
import time
(I got a nice vector class from someone else. It's large, and mostly likely not the problem.)
(INSERT CONTENTS OF VECTOR.PY FROM https://gist.github.com/mcleonard/5351452 HERE)
pygame.init()
#some global constants
BLUE = (0, 0, 255)
WHITE = (255,255,255)
diagnostic = False
SPAWN_TIME = 1 #number of seconds between creating new critters
FLOCK_LIMIT = 30 #number of critters at which the flock begins being culled
GUIDs = [0] #list of guaranteed unique IDs for identifying each critter
# Set the position of the OS window
position = (30, 30)
os.environ['SDL_VIDEO_WINDOW_POS'] = str(position[0]) + "," + str(position[1])
# Set the position, width and height of the screen [width, height]
size_x = 1000
size_y = 500
size = (size_x, size_y)
FRAMERATE = 60
SECS_FOR_DYING = 1
screen = pygame.display.set_mode(size)
screen.set_alpha(None)
pygame.display.set_caption("My Game")
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
def random_float(lower, upper):
num = random.randint(lower*1000, upper*1000)
return num/1000
def new_GUID():
num = GUIDs[-1]
num = num + 1
while num in GUIDs:
num += 1
GUIDs.append(num)
return num
class HeatBlock:
def __init__(self,_tlx,_tly,h,w):
self.tlx = int(_tlx)
self.tly = int(_tly)
self.height = int(h)+1
self.width = int(w)
self.heat = 255.0
self.registered = False
def register_tresspasser(self):
self.registered = True
self.heat = max(self.heat - 1, 0)
def cool_down(self):
if not self.registered:
self.heat = min(self.heat + 0.1, 255)
self.registered = False
def hb_draw_self(self):
screen.fill((255,int(self.heat),int(self.heat)), [self.tlx, self.tly, self.width, self.height])
class HeatMap:
def __init__(self, _h, _v):
self.h_freq = _h #horizontal frequency
self.h_rez = size_x/self.h_freq #horizontal resolution
self.v_freq = _v #vertical frequency
self.v_rez = size_y/self.v_freq #vertical resolution
self.blocks = []
def make_map(self):
h_size = size_x/self.h_freq
v_size = size_y/self.v_freq
for h_count in range(0, self.h_freq):
TLx = h_count * h_size #TopLeft corner, x
col = []
for v_count in range(0, self.v_freq):
TLy = v_count * v_size #TopLeft corner, y
col.append(HeatBlock(TLx,TLy,v_size,h_size))
self.blocks.append(col)
def hm_draw_self(self):
for col in self.blocks:
for block in col:
block.cool_down()
block.hb_draw_self()
def register(self, x, y):
#convert the given coordinates of the trespasser into a col/row block index
col = max(int(math.floor(x / self.h_rez)),0)
row = max(int(math.floor(y / self.v_rez)),0)
self.blocks[col][row].register_tresspasser()
class Critter:
def __init__(self):
self.color = (random.randint(1, 200), random.randint(1, 200), random.randint(1, 200))
self.linear_speed = random_float(20, 100)
self.radius = int(round(10 * (100/self.linear_speed)))
self.angular_speed = random_float(0.1, 2)
self.x = int(random.randint(self.radius*2, size_x - (self.radius*2)))
self.y = int(random.randint(self.radius*2, size_y - (self.radius*2)))
self.orientation = Vector(0, 1).rotate(random.randint(-180, 180))
self.sensor = Vector(0, 20)
self.sensor_length = 20
self.new_orientation = self.orientation
self.draw_bounds = False
self.GUID = new_GUID()
self.condition = 0 #0 = alive, [1-fps] = dying, >fps = dead
self.delete_me = False
def c_draw_self(self):
#if we're alive and not dying, draw our normal self
if self.condition == 0:
#diagnostic
if self.draw_bounds:
pygame.gfxdraw.rectangle(screen, [int(self.x), int(self.y), 1, 1], BLUE)
temp = self.orientation * (self.linear_speed * 20)
pygame.gfxdraw.line(screen, int(self.x), int(self.y), int(self.x + temp[0]), int(self.y + temp[1]), BLUE)
#if there's a new orientation, match it gradually
temp = self.new_orientation * self.linear_speed
#draw my body
pygame.gfxdraw.aacircle(screen, int(self.x), int(self.y), self.radius, self.color)
#draw a line indicating my new direction
pygame.gfxdraw.line(screen, int(self.x), int(self.y), int(self.x + temp[0]), int(self.y + temp[1]), BLUE)
#draw my sensor (a line pointing forward)
self.sensor = self.orientation.normalize() * self.sensor_length
pygame.gfxdraw.line(screen, int(self.x), int(self.y), int(self.x + self.sensor[0]), int(self.y + self.sensor[1]), BLUE)
#otherwise we're dying, draw our dying animation
elif 1 <= self.condition <= FRAMERATE*SECS_FOR_DYING:
#draw some lines in a spinningi circle
for num in range(0,10):
line = Vector(0, 1).rotate((num*(360/10))+(self.condition*23))
line = line*self.radius
pygame.gfxdraw.line(screen, int(self.x), int(self.y), int(self.x+line[0]), int(self.y+line[1]), self.color)
def print_self(self):
#diagnostic
print("==============")
print("radius:", self.radius)
print("color:", self.color)
print("linear_speed:", self.linear_speed)
print("angular_speed:", self.angular_speed)
print("x:", self.x)
print("y:", int(self.y))
print("orientation:", self.orientation)
def avoid_others(self, _flock):
for _critter in _flock:
#if the critter isn't ME...
if _critter.GUID is not self.GUID and _critter.condition == 0:
#and it's touching me...
if self.x - _critter.x <= self.radius + _critter.radius:
me = Vector(self.x, int(self.y))
other_guy = Vector(_critter.x, _critter.y)
distance = me - other_guy
#give me new orientation that's away from the other guy
if distance.norm() <= ((self.radius) + (_critter.radius)):
new_direction = me - other_guy
self.orientation = self.new_orientation = new_direction.normalize()
def update_location(self, elapsed):
boundary = '?'
while boundary != 'X':
boundary = self.out_of_bounds()
if boundary == 'N':
self.orientation = self.new_orientation = Vector(0, 1).rotate(random.randint(-20, 20))
self.y = (self.radius) + 2
elif boundary == 'S':
self.orientation = self.new_orientation = Vector(0,-1).rotate(random.randint(-20, 20))
self.y = (size_y - (self.radius)) - 2
elif boundary == 'E':
self.orientation = self.new_orientation = Vector(-1,0).rotate(random.randint(-20, 20))
self.x = (size_x - (self.radius)) - 2
elif boundary == 'W':
self.orientation = self.new_orientation = Vector(1,0).rotate(random.randint(-20, 20))
self.x = (self.radius) + 2
point = Vector(self.x, self.y)
self.x, self.y = (point + (self.orientation * (self.linear_speed*(elapsed/1000))))
boundary = self.out_of_bounds()
def update_orientation(self, elapsed):
#randomly choose a new direction, from time to time
if random.randint(0, 100) > 98:
self.choose_new_orientation()
difference = self.orientation.argument() - self.new_orientation.argument()
self.orientation = self.orientation.rotate((difference * (self.angular_speed*(elapsed/1000))))
def still_alive(self, elapsed):
return_value = True #I am still alive
if self.condition == 0:
return_value = True
elif self.condition <= FRAMERATE*SECS_FOR_DYING:
self.condition = self.condition + (elapsed/17)
return_value = True
if self.condition > FRAMERATE*SECS_FOR_DYING:
return_value = False
return return_value
def choose_new_orientation(self):
if self.new_orientation:
if (self.orientation.argument() - self.new_orientation.argument()) < 5:
rotation = random.randint(-300, 300)
self.new_orientation = self.orientation.rotate(rotation)
def out_of_bounds(self):
if self.x >= (size_x - (self.radius)):
return 'E'
elif self.y >= (size_y - (self.radius)):
return 'S'
elif self.x <= (0 + (self.radius)):
return 'W'
elif self.y <= (0 + (self.radius)):
return 'N'
else:
return 'X'
# -------- Main Program Loop -----------
# generate critters
flock = [Critter()]
# generate heat map
heatMap = HeatMap(60, 40)
heatMap.make_map()
# set some settings
last_spawn = time.clock()
run_time = time.perf_counter()
frame_count = 0
max_time = 0
ms_elapsed = 1
avg_fps = [1]
# Loop until the user clicks the close button.
done = False
while not done:
# --- Main event loop only processes one event
frame_count = frame_count + 1
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# --- Game logic should go here
#check if it's time to make another critter
if time.clock() - last_spawn > SPAWN_TIME:
flock.append(Critter())
last_spawn = time.clock()
if len(flock) >= FLOCK_LIMIT:
#if we're over the flock limit, cull the herd
counter = FLOCK_LIMIT
for critter in flock[0:len(flock)-FLOCK_LIMIT]:
#this code allows a critter to be "dying" for a while, to play an animation
if critter.condition == 0:
critter.condition = 1
elif not critter.still_alive(ms_elapsed):
critter.delete_me = True
counter = 0
#delete all the critters that have finished dying
while counter < len(flock):
if flock[counter].delete_me:
del flock[counter]
else:
counter = counter+1
#----loop on all critters once, doing all functions for each critter
for critter in flock:
if critter.condition == 0:
critter.avoid_others(flock)
if critter.condition == 0:
heatMap.register(critter.x, critter.y)
critter.update_location(ms_elapsed)
critter.update_orientation(ms_elapsed)
if diagnostic:
critter.print_self()
#----alternately, loop for each function. Speed seems to be similar either way
#for critter in flock:
# if critter.condition == 0:
# critter.update_location(ms_elapsed)
#for critter in flock:
# if critter.condition == 0:
# critter.update_orientation(ms_elapsed)
# --- Screen-clearing code goes here
# Here, we clear the screen to white. Don't put other drawing commands
screen.fill(WHITE)
# --- Drawing code should go here
#draw the heat_map
heatMap.hm_draw_self()
for critter in flock:
critter.c_draw_self()
#draw the framerate
myfont = pygame.font.SysFont("monospace", 15)
#average the framerate over 60 frames
temp = sum(avg_fps)/float(len(avg_fps))
text = str(round(((1/temp)*1000),0))+"FPS | "+str(len(flock))+" Critters"
label = myfont.render(text, 1, (0, 0, 0))
screen.blit(label, (5, 5))
# --- Go ahead and update the screen with what we've drawn.
pygame.display.update()
# --- Limit to 60 frames per second
#only run for 30 seconds
if time.perf_counter()-run_time >= 30:
done = True
#limit to 60fps
#add this frame's time to the list
avg_fps.append(ms_elapsed)
#remove any old frames
while len(avg_fps) > 60:
del avg_fps[0]
ms_elapsed = clock.tick(FRAMERATE)
#track longest frame
if ms_elapsed > max_time:
max_time = ms_elapsed
#print some stats once the program is finished
print("Count:", frame_count)
print("Max time since last flip:", str(max_time)+"ms")
print("Total Time:", str(int(time.perf_counter()-run_time))+"s")
print("Average time for a flip:", str(int(((time.perf_counter()-run_time)/frame_count)*1000))+"ms")
# Close the window and quit.
pygame.quit()
One thing you can already do to improve the performance is to use pygame.math.Vector2 instead of your Vector class, because it's implemented in C and therefore faster. Before I switched to pygame's vector class, I could have ~50 critters on the screen before the frame rate dropped below 60, and after the change up to ~100.
pygame.math.Vector2 doesn't have that argument method, so you need to extract it from the class and turn it into a function:
def argument(vec):
""" Returns the argument of the vector, the angle clockwise from +y."""
arg_in_rad = math.acos(Vector(0,1)*vec/vec.length())
arg_in_deg = math.degrees(arg_in_rad)
if vec.x < 0:
return 360 - arg_in_deg
else:
return arg_in_deg
And change .norm() to .length() everywhere in the program.
Also, define the font object (myfont) before the while loop. That's only a minor improvement, but every frame counts.
Another change that made a significant improvement was to streamline my collision-detection algorithm.
Formerly, I had been looping through every critter in the flock, and measuring the distance between it and every other critter in the flock. If that distance was small enough, I do something. That's n^2 checks, which is not awesome.
I'd thought about using a quadtree, but it didn't seem efficient to rebalance the whole tree every frame, because it will change every time a critter moves.
Well, I finally actually tried it, and it turns out that building a brand-new quadtree at the beginning of each frame is actually plenty fast. Once I have the tree, I pass it to the avoidance function where I just extract an intersection of any of the critters in that tree within a bounding box I care about. Then I just iterate on those neighbors to measure distances and update directions and whatnot.
Now I'm up to 150 or so critters before I start dropping frames (up from 40).
So the moral of the story is, trust evidence instead of intuition.

QCombobox bigger in size for the first time only

class RangeSelection(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
layout = QGridLayout(self)
self.setLayout(layout)
self._create_widgets()
layout.addWidget(self.select_combo, 1, 1)
layout.addWidget(self.stacked, 1, 2, 5, 1)
self.stacked.currentWidget().setSizePolicy(
QSizePolicy.Preferred, QSizePolicy.Preferred)
self.stacked.currentChanged.connect(self.onCurrentChanged)
def onCurrentChanged(self):
currentw = self.stacked.currentWidget()
currentw.adjustSize()
if currentw == self.releasew:
currentw.sizeAdjustPolicy = QComboBox.AdjustToContentsOnFirstShow
self.adjustSize()
def _create_widgets(self):
self.stacked = QStackedWidget()
self.datew = QCalendarWidget()
self.datew.setVerticalHeaderFormat(QCalendarWidget.
NoVerticalHeader)
self.stacked.addWidget(self.datew)
self.buildidw = QLineEdit()
self.stacked.addWidget(self.buildidw)
self.releasew = QComboBox()
self.releasew.addItems([str(k) for k in sorted(releases())])
self.stacked.addWidget(self.releasew)
self.revw = QLineEdit()
self.stacked.addWidget(self.revw)
self.select_combo = QComboBox()
self.select_combo.addItems(['date', 'buildid', 'release', 'changeset'])
self.select_combo.activated.connect(self.stacked.setCurrentIndex)
I have this code where I am having four widgets in the QStackedWidget. When I run this code and change my selection in self.select_combo from date to release, the self.releasew combobox initially shows up as same size as that of the QCalendarWidget( which obviously looks horrible ). But, when I change my selection from release to any other value and then back to release, the self.releasew combobox shows up in the size it should. Why is this happening? What is the solution to this problem?
Note: I am using PyQt4. Also note that widgets for buildid and changeset do not show any abnormal behaviour.
I removed the setSizePolicy and sizeAdjustPolicy code. I also removed the call to self.adjustSize(). This worked. Though, I don't know why.

Access windows for notebook in Tkinter

I have been trying to create an open windows which asks you for username and password before opening a notebook in Tkinter, I have both, but I don't know how to put them together. In other words, what I want is to open a notebook once the username and password requested are correct.
Thank you very much in advance!
What I have done so far is as follows:
import Tkinter
from Tkinter import *
import ttk
from ttk import * #Combobox Definition
import tkMessageBox #for Welcome Message
import Tkinter as tk # For Main Frame Definition
from Tkinter import Tk, Text, BOTH, W, N, E, S
from ttk import Frame, Button, Label, Style
root = Tk()
root.title("Model A")
root.minsize(400, 220)
root.maxsize(410, 240)
# start of Notebook (multiple tabs)
notebook = ttk.Notebook(root)
notebook.pack(fill='both', expand='yes')
notebook.pressed_index = None
# create a child frame for each page
frameOne = Tkinter.Frame(notebook, bg='white',width=560, height=100)
frameOne.pack(fill='both', expand=True)
# create the pages
notebook.add(frameOne, text='Simple calculation')
#Login Starts
failure_max = 8
passwords = [('name','password')]
def make_entry(parent, caption, width=None, **options):
tk.Label(parent, text=caption).pack(side=tk.TOP)
entry = tk.Entry(parent, **options)
if width:
entry.config(width=width)
entry.pack(side=tk.TOP, padx=10, fill=tk.BOTH)
return entry
def enter(event):
check_password()
def check_password(failures=[]):
if (user.get(), password.get()) in passwords:
root.destroy()
return
failures.append(1)
if sum(failures) >= failure_max:
root.destroy()
raise SystemExit('Unauthorized login attempt')
else:
root.title('Try again. Attempt %i/%i' % (sum(failures)+1, failure_max))
parent = Tkinter.Frame(notebook, padx=10, pady=18, bg='white')
parent.pack(fill=tk.BOTH, expand=True)
user = make_entry(parent, "User name:", 16, show='')
password = make_entry(parent, "Password:", 16, show="*")
b = tk.Button(parent,borderwidth=4,text="Login",width=10,pady=8,command=check_password)
b.pack(side=Tkinter.BOTTOM)
password.bind('<Return>', enter)
#Close Application Button
def quit(root):
root.destroy()
tk.Button(root, text="Close Application", command=lambda root=root:quit(root)).pack()
#Calculation Starts
def defocus(event):
event.widget.master.focus_set()
def multiply(*args):
try:
product.set(round(float(Num_One.get())*float(Num_Two.get())))
except ValueError:
pass
Num_One = StringVar()
Num_Two = StringVar()
product = DoubleVar()
ttk.Label(frameOne, text="Select First Number:").grid(column =3, row = 0)
NumOne_Select = Combobox(frameOne, values=("1", "2", "3","4", "5"),textvariable=Num_One)
NumOne_Select.grid(column=4, row=0, columnspan="5", sticky="nswe")
Num_One.trace("w", multiply)
ttk.Label(frameOne, text="Select Second Number:").grid(column =3, row = 6 )
NumTwo_Select = Combobox(frameOne, values=("1", "2", "3","4", "5"),textvariable=Num_Two)
NumTwo_Select.grid(column=4, row=6, columnspan="5", sticky="nswe")
Num_Two.trace("w", multiply)
ttk.Label(frameOne, text = "Product:").grid(column = 3, row = 8)
ttk.Label(frameOne, textvariable=product).grid(column = 4, row = 8)
user.focus_set()
parent.mainloop()
root.mainloop()
You have several things going wrong in your code:
you're calling mainloop twice; you should only ever call it once.
you shouldn't pack or grid widgets inside the notebook. You are packing a widget and then using notebook.add; omit the pack.
you are calling destroy on the root window if the password is good. This causes your application to exit. Don't call destroy.
Normally the way this is done is that the notebook is a child of the root window, and the username/password dialog is an instance of Toplevel. You can hide the root window and pop up the dialog, and then if the user logs in, you can destroy the dialog and un-hide the main window.