The initial goal is to reduce the height of a frame to hide its lower part. This does not seem to work as long as there are still active widgets in the zone. So I use the 'visible' property to hide these widgets and 'height_request' to manage the height of the frame. The statement
self.frSaisie.set_property('height_request', 160)
(start Section of the code and in the callback) is totally inoperative. I even tried hiding the box ... still without result.
In addition, the masking works when it is activated by the CheckButton (but not the resizing), but is not taken into account when launching the application (bottom of the code).
If anyone has an idea, thanks in advance.
Sorry for the code length.
import gi
gi.require_version('Gtk','3.0')
from gi.repository import Gtk
class Appli(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, window_position = 1)
self.connect('delete-event', Gtk.main_quit)
# wid actifs
etNom = Gtk.Entry()
etPrenom = Gtk.Entry()
btValider = Gtk.Button('Valider')
btEnregistrer = Gtk.Button('Enregistrer')
btSupprimer = Gtk.Button('Supprimer')
btEffacer = Gtk.Button('Effacer')
self.ckGerer = Gtk.CheckButton('Gérer...', margin = 12)
self.ckGerer.connect('toggled', self.Gerer)
# wid container
gdIdentite = Gtk.Grid(margin = 6)
self.gdFonctions = Gtk.Grid(margin = 6, halign = 3, row_spacing = 6, column_spacing = 6)
self.frSaisie = Gtk.Frame(label = ' Saisie ', margin = 6, height_request = 400)
# Remplissage Grid
gdIdentite.attach(Gtk.Label('Nom', xalign = 1,margin_right = 6),0,0,1,1)
gdIdentite.attach(etNom,1,0,1,1)
gdIdentite.attach(Gtk.Label('Prénom', xalign = 1,margin_right = 6),0,1,1,1)
gdIdentite.attach(etPrenom,1,1,1,1)
self.gdFonctions.attach(btValider,0,0,1,1)
self.gdFonctions.attach(btEnregistrer,1,0,1,1)
self.gdFonctions.attach(btSupprimer,0,1,1,1)
self.gdFonctions.attach(btEffacer,1,1,1,1)
# Remplissage Box + Frame
self.bxSaisie = Gtk.Box(orientation = Gtk.Orientation(1))
self.bxSaisie.pack_start(gdIdentite, False, False, 0)
self.bxSaisie.pack_start(self.ckGerer, False, False, 0)
self.bxSaisie.pack_start(self.gdFonctions, True, True, 0)
self.frSaisie.add(self.bxSaisie)
self.add(self.frSaisie)
# Start
self.gdFonctions.set_property('visible', False) # not running at start
self.frSaisie.set_property('height_request', 160) # never running
self.show_all()
def Gerer(self, etat):
if self.ckGerer.get_active():
self.gdFonctions.set_property('visible', True)
else:
self.gdFonctions.set_property('visible', False) # running
self.frSaisie.set_property('height_request', 160) # never running
Appli()
Gtk.main()
It works better to resize the top window:
def Gerer(self, etat):
if self.ckGerer.get_active():
self.gdFonctions.set_property('visible', True)
else:
self.gdFonctions.set_property('visible', False) # running
self.resize(50, 50) # never running
Finally I worked around the problem using the Gtk.AspectFrame widget. The behavior is what I expected.
I replaced the declaration of the frame:
self.frSaisie = Gtk.Frame(label = ' Saisie ', margin = 6, height_request = 300)
by
self.frSaisie = Gtk.AspectFrame(label = ' Saisie ', margin = 6, \
height_request = 100, yalign = 0.001)
and I slightly modified the callback to simplify things.
However, I still do not understand why this formatting - now triggered by the function femMini - does not apply to startup.
If anyone could explain to me ... Thank you in advance
class Appli(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, window_position = 1, height_request = 400)
self.connect('delete-event', Gtk.main_quit)
# wid actifs
etNom = Gtk.Entry()
etPrenom = Gtk.Entry()
btValider = Gtk.Button('Valider')
btEnregistrer = Gtk.Button('Enregistrer')
btSupprimer = Gtk.Button('Supprimer')
btEffacer = Gtk.Button('Effacer')
self.ckGerer = Gtk.CheckButton('Gérer...', margin = 12)
self.ckGerer.connect('toggled', self.Gerer)
# wid container
gdIdentite = Gtk.Grid(margin = 6)
self.gdFonctions = Gtk.Grid(margin = 6, halign = 3, row_spacing = 6, column_spacing = 6)
#self.frSaisie = Gtk.Frame(label = ' Saisie ', margin = 6, height_request = 300)
self.frSaisie = Gtk.AspectFrame(label = ' Saisie ', margin = 6, \
height_request = 100, yalign = 0.001)
# Remplissage Grid
gdIdentite.attach(Gtk.Label('Nom', xalign = 1,margin_right = 6),0,0,1,1)
gdIdentite.attach(etNom,1,0,1,1)
gdIdentite.attach(Gtk.Label('Prénom', xalign = 1,margin_right = 6),0,1,1,1)
gdIdentite.attach(etPrenom,1,1,1,1)
self.gdFonctions.attach(btValider,0,0,1,1)
self.gdFonctions.attach(btEnregistrer,1,0,1,1)
self.gdFonctions.attach(btSupprimer,0,1,1,1)
self.gdFonctions.attach(btEffacer,1,1,1,1)
# Remplissage Box + Frame
self.bxSaisie = Gtk.Box(orientation = Gtk.Orientation(1))
self.bxSaisie.pack_start(gdIdentite, False, False, 0)
self.bxSaisie.pack_start(self.ckGerer, False, False, 0)
self.bxSaisie.pack_start(self.gdFonctions, True, True, 0)
self.frSaisie.add(self.bxSaisie)
self.add(self.frSaisie)
# Start
self.fenMini()
self.show_all()
# Méthodes
def fenMini(self):
self.gdFonctions.set_property('visible', False)
self.frSaisie.set_property('height_request', 120)
def fenMaxi(self):
self.gdFonctions.set_property('visible', True)
# Callbacks
def Gerer(self, etat):
if self.ckGerer.get_active():
self.fenMaxi()
else:
self.fenMini()
Appli()
Gtk.main()
Related
This question already has answers here:
Pygame - Mouse clicks not getting detected
(2 answers)
Closed 2 years ago.
I am currently working on a CS50 project studying the AI required for tic-tac-toe. however I can't get the runner.py file to run, as I get the following error:
Traceback (most recent call last): File
"/Users/newtracksuit/Downloads/tictactoe/runner.py", line 57, in
click, _, _ = pygame.mouse.get_pressed() ValueError: too many values to unpack (expected 3)
here is the full code provided, I have yet to write any actual functionality to the tic-tac-toe program, Just need to understand why this is not working yet
import pygame
import sys
import time
import tictactoe as ttt
pygame.init()
size = width, height = 600, 400
# Colors
black = (0, 0, 0)
white = (255, 255, 255)
screen = pygame.display.set_mode(size)
mediumFont = pygame.font.Font("OpenSans-Regular.ttf", 28)
largeFont = pygame.font.Font("OpenSans-Regular.ttf", 40)
moveFont = pygame.font.Font("OpenSans-Regular.ttf", 60)
user = None
board = ttt.initial_state()
ai_turn = False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.fill(black)
# Let user choose a player.
if user is None:
# Draw title
title = largeFont.render("Play Tic-Tac-Toe", True, white)
titleRect = title.get_rect()
titleRect.center = ((width / 2), 50)
screen.blit(title, titleRect)
# Draw buttons
playXButton = pygame.Rect((width / 8), (height / 2), width / 4, 50)
playX = mediumFont.render("Play as X", True, black)
playXRect = playX.get_rect()
playXRect.center = playXButton.center
pygame.draw.rect(screen, white, playXButton)
screen.blit(playX, playXRect)
playOButton = pygame.Rect(5 * (width / 8), (height / 2), width / 4, 50)
playO = mediumFont.render("Play as O", True, black)
playORect = playO.get_rect()
playORect.center = playOButton.center
pygame.draw.rect(screen, white, playOButton)
screen.blit(playO, playORect)
# Check if button is clicked
click, _, _ = pygame.mouse.get_pressed()
if click == 1:
mouse = pygame.mouse.get_pos()
if playXButton.collidepoint(mouse):
time.sleep(0.2)
user = ttt.X
elif playOButton.collidepoint(mouse):
time.sleep(0.2)
user = ttt.O
else:
# Draw game board
tile_size = 80
tile_origin = (width / 2 - (1.5 * tile_size),
height / 2 - (1.5 * tile_size))
tiles = []
for i in range(3):
row = []
for j in range(3):
rect = pygame.Rect(
tile_origin[0] + j * tile_size,
tile_origin[1] + i * tile_size,
tile_size, tile_size
)
pygame.draw.rect(screen, white, rect, 3)
if board[i][j] != ttt.EMPTY:
move = moveFont.render(board[i][j], True, white)
moveRect = move.get_rect()
moveRect.center = rect.center
screen.blit(move, moveRect)
row.append(rect)
tiles.append(row)
game_over = ttt.terminal(board)
player = ttt.player(board)
# Show title
if game_over:
winner = ttt.winner(board)
if winner is None:
title = f"Game Over: Tie."
else:
title = f"Game Over: {winner} wins."
elif user == player:
title = f"Play as {user}"
else:
title = f"Computer thinking..."
title = largeFont.render(title, True, white)
titleRect = title.get_rect()
titleRect.center = ((width / 2), 30)
screen.blit(title, titleRect)
# Check for AI move
if user != player and not game_over:
if ai_turn:
time.sleep(0.5)
move = ttt.minimax(board)
board = ttt.result(board, move)
ai_turn = False
else:
ai_turn = True
# Check for a user move
click, _, _ = pygame.mouse.get_pressed()
if click == 1 and user == player and not game_over:
mouse = pygame.mouse.get_pos()
for i in range(3):
for j in range(3):
if (board[i][j] == ttt.EMPTY and tiles[i][j].collidepoint(mouse)):
board = ttt.result(board, (i, j))
if game_over:
againButton = pygame.Rect(width / 3, height - 65, width / 3, 50)
again = mediumFont.render("Play Again", True, black)
againRect = again.get_rect()
againRect.center = againButton.center
pygame.draw.rect(screen, white, againButton)
screen.blit(again, againRect)
click, _, _ = pygame.mouse.get_pressed()
if click == 1:
mouse = pygame.mouse.get_pos()
if againButton.collidepoint(mouse):
time.sleep(0.2)
user = None
board = ttt.initial_state()
ai_turn = False
pygame.display.flip()
pygame.mouse.get_pressed()
Returns a sequence of booleans representing the state of all the mouse buttons.
The number of buttons is either 4 or 6, that depends on the version of pygame. I recommend to get the state of a single button by subscription:
buttons = pygame.mouse.get_pressed()
if button[0] == 1:
# [...]
What is returned when you execute pygame.mouse.get_pressed()? I see (0, 0, 0) which is the three arguments your code expects.
You could work out what your code is returning and add the requisite number of underscores, but if you aren't interested in the remaining arguments, you can use * to handle the rest of the returned values, e.g.
click, *_ = pygame.mouse.get_pressed()
I was making a game where you chop wood in a forest every day and was doing the function to destroy a tree after 3 seconds by putting a SysFont at the bottom of the screen, counting down from three seconds which by then it would remove the tree. I binded the key Q to chop down the first tree(for testing purposes), but instead I got no removal of the tree, and no SysFont counting down - all it did was lag the game because of the time.sleep(1) i had put in. The entire code is below:
import pygame
import time
pygame.init()
root = pygame.display.set_mode((603, 573))
pygame.display.set_caption("Homework")
window_is_open = True
white = (255, 255, 255)
black = (0, 0, 0)
width = 10
leaves_width = 30
height = 20
leaves_height = 10
x = 0
tree_trunk_x = 10
y = 0
tree_trunk_y = 10
vel = 5
brown = (150, 75, 0)
green = (58, 95, 11)
tree_one_property = True
tree_two_property = True
tree_three_property = True
tree_four_property = True
tree_five_property = True
tree_six_property = True
tree_seven_property = True
tree_eight_property = True
tree_nine_property = True
tree_ten_property = True
tree_eleven_property = True
tree_twelve_property = True
tree_thirteen_property = True
tree_fourteen_property = True
tree_fifteen_property = True
tree_sixteen_property = True
tree_seventeen_property = True
tree_eighteen_property = True
tree_nineteen_property = True
tree_twenty_property = True
tree_twenty_one_property = True
tree_twenty_two_property = True
tree_twenty_three_property = True
tree_twenty_four_property = True
tree_twenty_five_property = True
def create_tree(tree_x, tree_y, tree):
if tree:
trunk_x = tree_x + 10
trunk_y = tree_y + 10
pygame.draw.rect(root, brown, (trunk_x, trunk_y, width, height))
pygame.draw.rect(root, green, (tree_x, tree_y, leaves_width, leaves_height))
def destroy_tree(tree_property_name):
count = pygame.font.SysFont('Tahoma', 18, True, False)
countdown = count.render('3', True, (0, 0, 0))
root.blit(countdown, (590, 569))
pygame.display.update()
time.sleep(1)
count = pygame.font.SysFont('Tahoma', 18, True, False)
countdown = count.render('2', True, (0, 0, 0))
root.blit(countdown, (590, 569))
pygame.display.update()
time.sleep(1)
count = pygame.font.SysFont('Tahoma', 18, True, False)
countdown = count.render('1', True, (0, 0, 0))
root.blit(countdown, (590, 569))
pygame.display.update()
time.sleep(1)
tree_property_name = False
root.fill(white)
while window_is_open:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
window_is_open = False
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT]:
x += vel
if keys[pygame.K_LEFT]:
x -= vel
if keys[pygame.K_UP]:
y -= vel
if keys[pygame.K_DOWN]:
y += vel
if keys[pygame.K_q]:
destroy_tree(tree_one_property)
root.fill(white)
font = pygame.font.SysFont('Tahoma', 18, True, False)
score = font.render('Score:', True, (0, 0, 0))
root.blit(score, (410, 0))
rectangle = pygame.draw.rect(root, (0, 0, 0), (x, y, width, 10))
tree_one = create_tree(0, 0, tree_one_property)
tree_two = create_tree(50, 0, tree_two_property)
tree_three = create_tree(100, 0, tree_three_property)
tree_four = create_tree(150, 0, tree_four_property)
tree_five = create_tree(200, 0, tree_five_property)
tree_six = create_tree(0, 50, tree_six_property)
tree_seven = create_tree(50, 50, tree_seven_property)
tree_eight = create_tree(100, 50, tree_eight_property)
tree_nine = create_tree(150, 50, tree_nine_property)
tree_ten = create_tree(200, 50, tree_ten_property)
tree_eleven = create_tree(0, 100, tree_eleven_property)
tree_twelve = create_tree(50, 100, tree_twelve_property)
tree_thirteen = create_tree(100, 100, tree_thirteen_property)
tree_fourteen = create_tree(150, 100, tree_fourteen_property)
tree_fifteen = create_tree(200, 100, tree_fifteen_property)
tree_sixteen = create_tree(0, 150, tree_sixteen_property)
tree_seventeen = create_tree(50, 150, tree_seventeen_property)
tree_eighteen = create_tree(100, 150, tree_eighteen_property)
tree_nineteen = create_tree(150, 150, tree_nineteen_property)
tree_twenty = create_tree(200, 150, tree_twenty_property)
tree_twenty_one = create_tree(0, 200, tree_twenty_one_property)
tree_twenty_two = create_tree(50, 200, tree_twenty_two_property)
tree_twenty_three = create_tree(100, 200, tree_twenty_three_property)
tree_twenty_four = create_tree(150, 200, tree_twenty_four_property)
tree_twenty_five = create_tree(200, 200, tree_twenty_five_property)
pygame.display.update()
pygame.quit()
It looks like you are drawing the font (almost) entirely off the bottom of the screen.The lines below:
root = pygame.display.set_mode((603, 573))
...
root.blit(countdown, (590, 569))
indicate that your screen has a height of 573 pixels. You are blit'ing your text with its top at 569, which is only 4 pixels onto the screen. In reality that likely means that the text is entirely off the bottom of the screen.
Try moving it a bit higher.
In fact you can actually get the size of the bounding box of the text surface countdown like this:
text_box_size = countdown.get_size()
See docs here. You can get the height and width of the text box like this and use that to determine the offset from the bottom of the screen you want to pass to blit().
I have edited this answer to add a response to the question in your comment asking why your tree was still rendering. This would be to much to add in a follow on comment.
In your code you have a method def destroy_tree(tree_property_name) and in it you try to update the variable tree_property_name and make it False. That would work if the variable was passed to the function as pass by reference, but in python that is not how arguments are passed. So when you set it to False inside the method all that does is change the value seen inside the scope of the method. The value seen by the caller of the function is not changed.
You can get more explanation by looking at the answer to How do I pass a variable by reference?:
Your code would be significantly cleaner if you made the trees into a class. It would also allow you to be able to change the internal values in the class when the class is passed into a method.
I want to add a function that updates the value of the self.ScoreP variable
I have a number on the screen, which prints out the current value of the ScoreP (updateScoreBoard()). It is accurate and works perfectly, but I am also printing out getScoreP. ScoreP prints 0 no matter what the score currently is.
import pygame
class ScoreBoard():
def __init__(self):
self.WIDTH = 1024
self.HEIGHT = 576
self.WHITE = (255, 255, 255)
self.BLACK = (0,0,0)
self.minFont = "font/Minecraft.ttf"
self.scoreFont = pygame.font.Font(self.minFont, 75)
self.ScoreP = 0
self.ScorePStr = str(self.ScoreP)
self.ScoreO = 0
self.ScoreOStr = str(self.ScoreO)
self.ScorePWidth, self.ScorePHeight = self.scoreFont.size(str(self.ScoreP))
self.ScoreOWidth, self.ScoreOHeight = self.scoreFont.size(str(self.ScoreO))
self.ScorePX = (self.WIDTH/2)-self.ScorePWidth*2
self.ScorePY = 10
self.ScoreOX = self.WIDTH/2 + self.ScoreOWidth
self.ScoreOY = 10
def updateScoreBoard(self, screen):
pygame.draw.rect(screen, self.BLACK, [self.ScorePX, self.ScorePY, self.ScorePWidth, self.ScorePHeight])
scorePRender = self.scoreFont.render("{}".format(self.ScoreP), False, self.WHITE)
screen.blit(scorePRender, (self.ScorePX, self.ScorePY))
pygame.draw.rect(screen, self.BLACK, [self.ScoreOX, self.ScoreOY, self.ScoreOWidth, self.ScoreOHeight])
scoreORender = self.scoreFont.render("{}".format(self.ScoreO), False, self.WHITE)
screen.blit(scoreORender, (self.ScoreOX, self.ScoreOY))
pygame.display.flip()
def updateScore(self, playerIncrease, opponentIncrease):
self.ScoreP += playerIncrease
self.ScorePStr = self.ScoreP
self.ScoreO += opponentIncrease
self.ScoreOStr = self.ScoreO
def getScoreP(self):
return self.ScoreP
However, the getScore function prints out 0
Even though, the game properly keeps track of and redraws the score
Thank you in advance
Here I don't think I changed much, but it works. Also next time give us your whole code including how you test it, because the problem may be there. I added a test at the end that you can delete.
import pygame
import random
class ScoreBoard:
def __init__(self,w,h):
pygame.font.init()
self.WIDTH = w
self.HEIGHT = h
self.screen = pygame.display.set_mode((1024,576))
self.WHITE = (255, 255, 255)
self.BLACK = (0,0,0)
self.minFont = None
self.scoreFont = pygame.font.Font(self.minFont, 75)
self.ScoreP = 0
self.ScoreO = 0
self.ScorePWidth, self.ScorePHeight = self.scoreFont.size(str(self.ScoreP))
self.ScoreOWidth, self.ScoreOHeight = self.scoreFont.size(str(self.ScoreO))
self.ScorePX = (self.WIDTH/2)-self.ScorePWidth*2
self.ScorePY = 10
self.ScoreOX = self.WIDTH/2 + self.ScoreOWidth
self.ScoreOY = 10
def updateScoreBoard(self):
self.ScorePWidth, self.ScorePHeight = self.scoreFont.size(str(int(self.ScoreP)))
self.ScoreOWidth, self.ScoreOHeight = self.scoreFont.size(str(int(self.ScoreO)))
screen = self.screen
screen.fill(self.WHITE)
pygame.draw.rect(screen, self.BLACK, [self.ScorePX, self.ScorePY, self.ScorePWidth, self.ScorePHeight])
scorePRender = self.scoreFont.render("{}".format(int(self.ScoreP)), False, self.WHITE)
screen.blit(scorePRender, (self.ScorePX, self.ScorePY))
pygame.draw.rect(screen, self.BLACK, [self.ScoreOX, self.ScoreOY, self.ScoreOWidth, self.ScoreOHeight])
scoreORender = self.scoreFont.render(str(int(self.ScoreO)), False, self.WHITE)
screen.blit(scoreORender, (self.ScoreOX, self.ScoreOY))
pygame.display.flip()
def updateScore(self, playerIncrease, opponentIncrease):
self.ScoreP += playerIncrease
self.ScoreO += opponentIncrease
def getScoreP(self):
return self.ScoreP
running = True
a = ScoreBoard(1024,576)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
break
a.updateScore(random.random()/10,random.random()/10)
a.updateScoreBoard()
I've tried to add the GUI (tkinter) into my script, but to no avail. If anyone can help me, i would be so grateful. I'm using Python 3.6 and i think the latest opencv?
I have only started programming 2 weeks ago. So, kinda new into all this. Basically, I want to create a window that just pick the image from my folder and then process it through the script so that whenever i want to use another image, i don't have to change the script. I hope that make sense..
this is the script that i took from Chris Dahms from youtube, and managed to change it to what I want.
import cv2
import numpy as np
import os
import DetectChars
import DetectPlates
import PossiblePlate
SCALAR_BLACK = (0.0, 0.0, 0.0)
SCALAR_WHITE = (255.0, 255.0, 255.0)
SCALAR_YELLOW = (0.0, 255.0, 255.0)
SCALAR_GREEN = (0.0, 255.0, 0.0)
SCALAR_CYAN = (255.0, 255.0, 0.0)
showSteps = False
def main():
blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN()
if blnKNNTrainingSuccessful == False:
print ("\nerror: KNN training was not successful\n")
return
imgOriginalScene = cv2.imread("CAR/Malaysia/22.jpg")
if imgOriginalScene is None:
print ("\nerror: image not read from file \n\n")
os.system("pause")
return
if imgOriginalScene is None:
print ("\nerror: image not read from file \n\n")
os.system("pause")
return
listOfPossiblePlates = DetectPlates.detectPlatesInScene(imgOriginalScene)
listOfPossiblePlates = DetectChars.detectCharsInPlates(listOfPossiblePlates)
cv2.imshow("imgOriginalScene", imgOriginalScene)
if len(listOfPossiblePlates) == 0:
print ("\nno license plates were detected\n")
else:
listOfPossiblePlates.sort(key = lambda possiblePlate: len(possiblePlate.strChars), reverse = True)
licPlate = listOfPossiblePlates[0]
cv2.imshow("Image Plate", licPlate.imgPlate)
cv2.imshow("Image Threshold", licPlate.imgThresh)
if len(licPlate.strChars) == 0:
print ("\nno characters were detected\n\n")
return
drawRedRectangleAroundPlate(imgOriginalScene, licPlate)
print ("\nlicense plate read from image = " + licPlate.strChars + "\n")
print ("----------------------------------------")
writeLicensePlateCharsOnImage(imgOriginalScene, licPlate)
cv2.imshow("imgOriginalScene", imgOriginalScene)
cv2.imwrite("imgOriginalScene.png", imgOriginalScene)
cv2.waitKey(0)
return
def drawRedRectangleAroundPlate(imgOriginalScene, licPlate):
p2fRectPoints = cv2.boxPoints(licPlate.rrLocationOfPlateInScene)
cv2.line(imgOriginalScene, tuple(p2fRectPoints[0]), tuple(p2fRectPoints[1]), SCALAR_RED, 2)
cv2.line(imgOriginalScene, tuple(p2fRectPoints[1]), tuple(p2fRectPoints[2]), SCALAR_RED, 2)
cv2.line(imgOriginalScene, tuple(p2fRectPoints[2]), tuple(p2fRectPoints[3]), SCALAR_RED, 2)
cv2.line(imgOriginalScene, tuple(p2fRectPoints[3]), tuple(p2fRectPoints[0]), SCALAR_RED, 2)
def writeLicensePlateCharsOnImage(imgOriginalScene, licPlate):
ptCenterOfTextAreaX = 0
ptCenterOfTextAreaY = 0
ptLowerLeftTextOriginX = 0
ptLowerLeftTextOriginY = 0
sceneHeight, sceneWidth, sceneNumChannels = imgOriginalScene.shape
plateHeight, plateWidth, plateNumChannels = licPlate.imgPlate.shape
intFontFace = cv2.FONT_HERSHEY_SIMPLEX
fltFontScale = float(plateHeight) / 30.0
intFontThickness = int(round(fltFontScale * 2))
textSize, baseline = cv2.getTextSize(licPlate.strChars, intFontFace, fltFontScale, intFontThickness)
( (intPlateCenterX, intPlateCenterY), (intPlateWidth, intPlateHeight), fltCorrectionAngleInDeg ) = licPlate.rrLocationOfPlateInScene
intPlateCenterX = int(intPlateCenterX)
intPlateCenterY = int(intPlateCenterY)
ptCenterOfTextAreaX = int(intPlateCenterX)
if intPlateCenterY < (sceneHeight * 0.75):
ptCenterOfTextAreaY = int(round(intPlateCenterY)) + int(round(plateHeight * 1.6))
else:
ptCenterOfTextAreaY = int(round(intPlateCenterY)) - int(round(plateHeight * 1.6))
textSizeWidth, textSizeHeight = textSize
ptLowerLeftTextOriginX = int(ptCenterOfTextAreaX - (textSizeWidth / 2))
ptLowerLeftTextOriginY = int(ptCenterOfTextAreaY + (textSizeHeight / 2))
cv2.putText(imgOriginalScene, licPlate.strChars, (ptLowerLeftTextOriginX, ptLowerLeftTextOriginY), intFontFace, fltFontScale, SCALAR_CYAN, intFontThickness)
if __name__ == "__main__":
main()
cv2.waitKey()
cv2.destroyAllWindows()
Pre-processing stage
# Preprocess.py
import numpy as np
import math
# module level variables ##########################################################################
GAUSSIAN_SMOOTH_FILTER_SIZE = (5, 5)
ADAPTIVE_THRESH_BLOCK_SIZE = 19
ADAPTIVE_THRESH_WEIGHT = 9
def preprocess(imgOriginal):
imgGrayscale = extractValue(imgOriginal)
imgMaxContrastGrayscale = maximizeContrast(imgGrayscale)
height, width = imgGrayscale.shape
grayscaled = cv2.cvtColor(imgOriginal,cv2.COLOR_BGR2GRAY)
imgBlurred = np.zeros((height, width, 1), np.uint8)
imgBlurred, otsu = cv2.threshold(grayscaled,125,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
imgThresh = cv2.medianBlur(otsu,5)
return imgGrayscale, imgThresh
# end function
def extractValue(imgOriginal):
height, width, numChannels = imgOriginal.shape
imgHSV = np.zeros((height, width, 3), np.uint8)
imgHSV = cv2.cvtColor(imgOriginal, cv2.COLOR_BGR2HSV)
imgHue, imgSaturation, imgValue = cv2.split(imgHSV)
return imgValue
# end function
def maximizeContrast(imgGrayscale):
height, width = imgGrayscale.shape
imgTopHat = np.zeros((height, width, 1), np.uint8)
imgBlackHat = np.zeros((height, width, 1), np.uint8)
structuringElement = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
imgTopHat = cv2.morphologyEx(imgGrayscale, cv2.MORPH_TOPHAT, structuringElement)
imgBlackHat = cv2.morphologyEx(imgGrayscale, cv2.MORPH_BLACKHAT, structuringElement)
imgGrayscalePlusTopHat = cv2.add(imgGrayscale, imgTopHat)
imgGrayscalePlusTopHatMinusBlackHat = cv2.subtract(imgGrayscalePlusTopHat, imgBlackHat)
return imgGrayscalePlusTopHatMinusBlackHat
# end function
If all you are wanting is a window to select a file then this should work.
import Tkinter
from Tkinter import *
import tkSimpleDialog
from tkFileDialog import askopenfilename
master = Tk()
master.withdraw()
my_file = askopenfilename()
mainloop()
i recommend Gtk3 for your GUI.
here's a simple Gtk window with button:
#!/usr/bin/env python3
import gi
gi.require_version( 'Gtk', '3.0' )
from gi.repository import Gtk
class Window( Gtk.Window ):
def __init__( self ):
Gtk.Window.__init__( self )
self.connect( 'destroy', lambda q: Gtk.main_quit() )
button = Gtk.Button( "Gtk.Button" )
button.connect( "clicked", self.on_button_clicked )
grid = Gtk.Grid( )
grid.attach( button, 0, 0, 1, 1 )
self.add( grid )
self.show_all()
def on_button_clicked( self, button ):
print( "Gtk.Button was clicked" )
w = Window()
Gtk.main()
I've made a simple gui age converter app but i want to change its bg color to black.
The problem is in the ttk frame.i don't know how to configure its bg color.
I have tried different methods but that didn't work.
i would be grateful if you guys could help.
here is the code
from tkinter import *
from tkinter import ttk
from PIL import Image
def calculate(*args):
try:
age_sec = int(age.get())
age_sec = age_sec * 12 * 365 * 24 * 60 * 60
age_seconds.set(age_sec)
except:
age_seconds.set('Either the field is empty or \n value is not numeric.')
root = Tk()
root.title("Converter")
root.configure(background="black")
mainframe = ttk.Frame(root, padding = "6 6 12 12")
mainframe.grid(column = 0, row = 0, sticky = (N, W, E, S))
mainframe.columnconfigure(0, weight = 1)
mainframe.rowconfigure(0, weight = 1)
#mainframe['borderwidth'] = 2
#mainframe['relief'] = 'groove'
age = StringVar()
age_seconds = StringVar()
ttk.Label(mainframe, foreground = "#4D4E4F", text = "Enter your Age: ").grid(column = 1, row = 1, sticky = E)
age_entry = ttk.Entry(mainframe, width = 30, textvariable = age)
age_entry.grid(column = 2, row = 1, sticky = (W, E))
ttk.Label(mainframe, foreground = "#4D4E4F", text = "your age in seconds is ").grid(column = 1, row = 2, sticky = (E))
ttk.Label(mainframe, textvariable = age_seconds, background = "lightyellow", foreground = "#727475", width = 30).grid(column = 2, row = 2, sticky = W)
#Mouse Events...\\
butt_image = PhotoImage(file = 'images.gif')
ttk.Button(mainframe, compound = TOP, text = "Hit Now", image =butt_image, cursor = "hand2", width= 30, command = calculate).grid(column = 2, row = 4, sticky = W)
l2 = ttk.Label(mainframe,foreground = "#4D4E4F", text = "Mouse Events: ").grid(column = 1, row = 3, sticky = E)
l = ttk.Label(mainframe,background = "lightyellow", foreground = "#727475", text = 'Measurement is starting...', width = 30)
l.grid(column = 2, row = 3, sticky = W)
l.bind('<Enter>', lambda e: l.configure(text = 'Moved Mouse Inside'))
l.bind('<Leave>', lambda e: l.configure(text = 'Mouse Moved Out'))
l.bind('<1>', lambda e: l.configure(text = 'left Mouse clicked'))
l.bind('<Double-1>', lambda e: l.configure(text = 'Double clicked'))
l.bind('<B1-Motion>', lambda e: l.configure(text = 'Left button drag to %d, %d' %(e.x, e.y)))
image = PhotoImage(file = 'waves.gif')
ttk.Label(mainframe, compound = CENTER, text = "Image text", font = ('roman', 9, 'normal'), foreground ='green', image = image).grid(column = 3, row = 1, sticky = (N, E))
#if '__name__' == '__main__':
for child in mainframe.winfo_children(): child.grid_configure(padx = 15, pady = 15)
age_entry.focus()
root.bind('<Return>', calculate)
root.mainloop()
A ttk.Frame does not have a background / bg option. To change it you need to use style.
See ttk.Frame Info
If you don't really need to use a ttk.Frame you can just switch to a tkinter.Frame