Unusual Syntax Error in PyGame using Eclipse - eclipse

import pygame
import time
import random
from __builtin__ import quit
pygame.init()
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (200,0,0)
green = (0,200,0)
bright_red = (255,0,0)
bright_green = (0,255,0)
ship_width = 73
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Galaxia Remastered')
clock = pygame.time.Clock()
background = pygame.image.load('space1.png')
background = pygame.transform.scale(background, (800,600))
shipImg = pygame.image.load('ship1.png')
shipImg = pygame.transform.scale(shipImg, (73,73))
mobImg = pygame.image.load('ufo.png')
mobImg = pygame.transform.scale(mobImg, (100,100))
def mobs_dodged(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: "+str(count), True, white)
gameDisplay.blit(text,(0,0))
def mobs(mobx, moby, mobw, mobh):
gameDisplay.blit(mobImg,(mobx,moby))
def ship(x,y):
gameDisplay.blit(shipImg,(x,y))
def text_objects(text,font):
textSurface = font.render(text, True, white)
return textSurface, textSurface.get_rect()
def message_display(text):
font = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects(text,font)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf,TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
message_display('You Crashed!')
def button(msg,x,y,w,h,ic,ac):
mouse = pygame.mouse.get_pos()
if x + w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(gameDisplay, ac, (x,y,w,h))
else:
pygame.draw.rect(gameDisplay,ic, (x,y,w,h))
font = pygame.font.Font('freesansbold.ttf',20)
textSurf, textRect = text_objects(msg, font)
textRect.center = ((x+(w/2)),(y+(h/2))
gameDisplay.blit(textSurf, textRect)
The last line gives me an invalid syntax error, highlighting the "gameDisplay". After looking around myself, there was an "import gameDisplay from..." another file I had within the project. I thought that it would be fixed if I deleted the line, however it stated "unresolved import". I restarted Ecplise and cleaned my project multiple times but it still doesn't work. I sent the program to my other computer and it still gets the same error. When I remove the "gameDisplay" line, it tells me that there is an invalid syntax in "def game_intro():".
All help would be greatly appreciated.

It looks like you got one mismatched paranthese on line 74
Just remove the very first one on that line and your code should work just fine again..
textRect.center = (x+(w/2)),(y+(h/2))

Related

how to get rid of padding around Gtk.Image in Gtk.Box / Gtk.Grid in gtk4?

I'm trying to write a simple GUI using Gtk4 (in Python), but I'm having trouble with getting rid of padding (and I don't understand why the padding is there).
The goal is pretty simple - I need a Gtk.Grid showing a bunch of images with some basic metadata. AFAICS a good way to do that is Window -> ScrollWindow -> Grid -> Box -> (Image + Label). And in general this works, except that the images have a lot of top/bottom padding, so the labels have a lot of empty space around, which I don't like but can't get rid of it :-(
See this screenshot
Here's a simple example demonstrating this:
import gi
import sys
gi.require_version('Gtk', '4.0')
from gi.repository import Gtk, GdkPixbuf
def create_image(file_name, img_width, cssProvider = None):
info = 'file:' + file_name
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
# box.get_style_context().add_provider(cssProvider, Gtk.STYLE_PROVIDER_PRIORITY_USER)
# box.add_css_class('thumbnail')
box.set_hexpand(True)
# add image to top
pixbuf = GdkPixbuf.Pixbuf.new_from_file(file_name)
# calculate height to keep width and aspect ratio
img_height = pixbuf.get_height() * img_width / pixbuf.get_width()
image = Gtk.Image.new_from_pixbuf(pixbuf)
image.set_size_request(img_height, img_width)
# image.get_style_context().add_provider(cssProvider, Gtk.STYLE_PROVIDER_PRIORITY_USER)
# image.add_css_class('thumbnail-image')
box.append(image)
# add label to bottom
label = Gtk.Label(label=info)
# label.get_style_context().add_provider(cssProvider, Gtk.STYLE_PROVIDER_PRIORITY_USER)
# label.add_css_class('thumbnail-label')
box.append(label)
return box
class MainWindow(Gtk.ApplicationWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.cssProvider = None
# self.cssProvider = Gtk.CssProvider()
# self.cssProvider.load_from_data(b"""
#.thumbnail {background-color: white; color: black; border: 1px solid #ddd; margin: 5px; padding: 0; }
#.thumbnail-label { font-size: 12pt; margin: 0; padding: 0; }
#.thumbnail-image { margin: 0; padding: 0; }
#.green { background-color: #bfb; }""")
self.set_default_size(900, 600)
self.set_title("MyApp")
self.grid = Gtk.Grid()
self.window = Gtk.ScrolledWindow()
self.window.set_child(self.grid)
self.set_child(self.window)
idx = 0
prev = None
for idx in range(0,20):
# 4 columns
i = int(idx / 4)
j = int(idx % 4)
image = create_image('frog.jpg', 1920/4 - 10, self.cssProvider)
self.grid.attach(image, j, i, 1, 1)
class MyApp(Gtk.Application):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.connect('activate', self.on_activate)
def on_activate(self, app):
self.win = MainWindow(application=app)
self.win.present()
app = MyApp(application_id="com.example.GtkApplication")
app.run(sys.argv)
This needs an image called 'frog.jpg', e.g. this one.
The sizes are meant to work on 1920x1080, with 4 columns. I'm sure it could be done more dynamic (i.e. to work better with resized windows etc.), but I believe that's a separate issue.
I've tried a bunch of things, including styling using CSS, etc. (which is commented-out in the sample).
I also experimented with setting hexpand/vexpand on different widgets, not adding the label, and various similar things.
Apparently using Gtk.Picture instead of Gtk.Image solves the issue - with Picture there's no unwanted empty space/padding. Seems a bit confusing, considering Picture/Image are often used as synonyms. Maybe it's in the gtk docs somewhere, but I don't see it - certainly not without reading between the lines. I see some discussion of "natural size" but I don't see how'd that imply this behavior. Anyway, if others face the same issue, try using Gtk.Picture.

How to change tab width in scalafmt

I'm using VS code with metal scala extension and cannot get my code to format properly. I want to have 8 spaces tab width for everything. This is my .scalafmt.conf
version = "2.0.0-RC4"
maxColumn = 80
continuationIndent.callSite = 8
continuationIndent.defnSite = 8
Then I press Ctrl+Shift+I to format the document. Only the call sites are aligned with 8 spaces, the definition sites are aligned to 2 spaces only.
This is what my formatted code looks like.
final class Goods(
_food: Int = 0,
_materials: Int = 0,
_products: Int = 0,
_fuel: Int = 0
) {
var raw = Array(_food, _materials, _products, _fuel)
def food: Int = raw(0)
def materials: Int = raw(1)
def products: Int = raw(2)
def fuel: Int = raw(3)
def weight = raw.sum
}
Why isn't the body of the class aligned with 8 space?
Because the developers of scalafmt arbitrarily don't want you to have control over your own tab width. This is the main reason I'm using scalariform instead.
https://github.com/scalameta/scalafmt/issues/1493

pyglet label not showing on screen on draw() with OpenAI gym render

I'm using a wrapper of OpenAI gym to create a graphical representation of a problem. For that, I'm drawing a circle with the given wrapper and then try to add some text.
My issue is, that only the circle shows, but the text label does not appear. Any suggestions on how I can make the text visible would be highly appreciated. Below a minimal example, that show the problem:
import pyglet
from gym.envs.classic_control import rendering
screen_width = 600
screen_height = 400
table_radius = 200
viewer = rendering.Viewer(screen_width, screen_height + 20)
table = rendering.make_circle(radius=table_radius, filled=False)
table_trans = rendering.Transform()
table.add_attr(table_trans)
table_trans.set_translation(screen_width / 2, screen_height / 2)
viewer.add_geom(table)
text = 'This is a test but it is not visible'
label = pyglet.text.Label(text, font_size=36,
x=10, y=10, anchor_x='left', anchor_y='bottom',
color=(255, 123, 255, 255))
label.draw()
viewer.render(return_rgb_array=False)
input()
What worked for me is to manually implement the render function and insert the label after the tranform.disable()
## Content of the render function
glClearColor(1, 1, 1, 1)
self.viewer.window.clear()
self.viewer.window.switch_to()
self.viewer.window.dispatch_events()
self.viewer.transform.enable()
for geom in self.viewer.geoms:
geom.render()
for geom in self.viewer.onetime_geoms:
geom.render()
self.viewer.transform.disable()
# Text
label = pyglet.text.Label(
"Hello, world",
font_name="Times New Roman",
font_size=36,
x=100,
y=100,
anchor_x="center",
anchor_y="center",
color=(255, 0, 0, 255),
)
label.draw()
arr = None
...
please try this code:
import pyglet
from gym.envs.classic_control import rendering
class DrawText:
def __init__(self, label:pyglet.text.Label):
self.label=label
def render(self):
self.label.draw()
screen_width = 600
screen_height = 400
table_radius = 200
viewer = rendering.Viewer(screen_width, screen_height + 20)
table = rendering.make_circle(radius=table_radius, filled=False)
table_trans = rendering.Transform()
table.add_attr(table_trans)
table_trans.set_translation(screen_width / 2, screen_height / 2)
viewer.add_geom(table)
text = 'This is a test but it is not visible'
label = pyglet.text.Label(text, font_size=36,
x=10, y=10, anchor_x='left', anchor_y='bottom',
color=(255, 123, 255, 255))
label.draw()
viewer.add_geom(DrawText(label))
viewer.render(return_rgb_array=False)
input()

PySide: Changing resize/growth direction of a window

I have popup being created along the edge of a window and I'd like it to expand the popup as the user types into its text field. This currently works, but the window is expanding to the right. Instead, I'd like the popup to expand to the left (and keep the right edge anchored in place).
My closest example that's kind of working is below. In it, I'm getting the size of the popup with every text input and then moving the popup based on its new size. I feel like this should work, but its not.
On the first text input the popup jumps to the left edge of my screen (x transformation only). On the second text input the popup jumps back to its original position. On a third text input the popup jumps back to the left edge of the screen. On the fourth input... You get the idea. I'd also like to mention that the overall growth of the window looks like it's growing from the center of the popup and not from the right edge.
I've noticed that after the button is clicked it remains highlighted until my mouse passes over it. Could this contributing to the problem?
Any thoughts or a better way to achieve this effect would be great, thanks!
from PySide import QtCore, QtGui
import maya.OpenMayaUI as mui
from shiboken import wrapInstance
def get_parent():
ptr = mui.MQtUtil.mainWindow()
return wrapInstance( long( ptr ), QtGui.QWidget )
############################################
class Tool_Window(QtGui.QDialog):
def __init__(self, parent = get_parent() ):
super(Tool_Window, self).__init__(parent)
# Commands
self.move_UI()
self.create_gui()
self.create_layout()
self.create_connections()
#-------------------------------------------
def create_gui(self):
self.button1 = QtGui.QPushButton()
self.button1.setMaximumWidth(50)
self.button2 = QtGui.QPushButton()
self.button2.setMaximumWidth(50)
self.button3 = QtGui.QPushButton()
self.button3.setMaximumWidth(50)
#-------------------------------------------
def create_layout(self):
layout = QtGui.QVBoxLayout()
layout.addWidget(self.button1)
layout.addWidget(self.button2)
layout.addWidget(self.button3)
blank_layout = QtGui.QVBoxLayout()
main_layout = QtGui.QHBoxLayout( self )
main_layout.addLayout(blank_layout)
main_layout.addLayout(layout)
layout.addStretch()
self.setLayout(layout)
#-------------------------------------------
def move_UI( self ):
''' Moves the UI to the cursor's position '''
pos = QtGui.QCursor.pos()
self.move(pos.x()+20, pos.y()+15)
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
def create_connections(self):
# Left click
self.button1.clicked.connect( self.on_left_click1 )
self.button2.clicked.connect( self.on_left_click2 )
self.button3.clicked.connect( self.on_left_click3 )
# Right click delete
delete = QtGui.QAction(self)
delete.setText("remove")
delete.triggered.connect(self.remove_button)
self.addAction(delete)
#-----#-----#-----#-----#-----#-----#-----#-----#-----#
def remove_button(self):
self.deleteLater()
def on_left_click1(self):
self.popup = Popup_Window( self, self.button1 ) # Passing button in so I can get it's position
self.popup.show()
def on_left_click2(self):
self.popup = Popup_Window( self, self.button2 )
self.popup.show()
def on_left_click3(self):
self.popup = Popup_Window( self, self.button3 )
self.popup.show()
############################################
class Popup_Window( QtGui.QDialog ):
def __init__( self, toolWindow, button ):
super( Popup_Window, self ).__init__()
self.__popup_filter = ClosePopupFilter()
self.installEventFilter(self.__popup_filter)
self.setWindowFlags(QtCore.Qt.Popup)
'''
self.setWindowFlags(QtCore.Qt.FramelessWindowHint |
QtCore.Qt.WindowStaysOnTopHint |
QtCore.Qt.CustomizeWindowHint |
QtCore.Qt.Tool)
'''
self.button_pos = button
self.toolWindow = toolWindow
self.setAttribute( QtCore.Qt.WA_DeleteOnClose )
self.resize(100, 100)
# Commands
self.create_gui()
self.create_layout()
self.create_connections()
self.move_UI()
#-------------------------------------------
def move_UI( self ): # Method that I use to place the popup window initially
self.line_edit.setFocus()
# Get button position
self.btn_global_point = self.button_pos.mapToGlobal(self.button_pos.rect().topLeft())
print self.btn_global_point
# Get window position
self.win_global_point = self.toolWindow.mapToGlobal(self.rect().topLeft())
print self.win_global_point
# Get popup Size
self.popup_size = self.mapToGlobal(self.rect().topRight())
print self.popup_size
# Move the window
self.move((self.win_global_point.x()-self.popup_size.x()), self.btn_global_point.y())
#-------------------------------------------
def create_gui( self ):
''' Visible GUI stuff '''
self.my_label = QtGui.QLabel("default text")
self.line_edit = QtGui.QLineEdit()
self.line_edit.setMaxLength( 30 )
self.push_btn = QtGui.QPushButton( "Hey" )
self.push_btn.setMaximumWidth( 30 )
#-------------------------------------------
def create_layout( self ):
self.button_layout = QtGui.QVBoxLayout()
self.button_layout.addWidget( self.my_label )
self.button_layout.addWidget( self.line_edit )
self.button_layout.addWidget( self.push_btn )
#self.button_layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(self.button_layout)
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
def create_connections( self ):
self.line_edit.textChanged.connect( self.on_text_changed )
#-----#-----#-----#-----#-----#-----#-----#-----#-----#
def on_text_changed( self ):
typed_name = self.line_edit.text()
self.my_label.setText(typed_name)
self.move_UI() # I reuse the move method to move the ui on text edit
############################################
class ClosePopupFilter(QtCore.QObject):
''' Close popup window '''
def eventFilter(self, target, event):
if event.type() == QtCore.QEvent.WindowDeactivate:
target.close()
return False
if __name__ == '__main__':
# Things to fix PySide Maya bug
try:
test_ui.close()
test_ui.deleteLater()
except:
pass
test_ui = Tool_Window()
test_ui.show()
try:
test_ui.show()
except:
test_ui.close()
test_ui.deleteLater()
I've trimmed a little bit the code you provided in the OP and tried to put together an example that address your particular issue.
Some of the modifications I've done to the code:
trigger the move_UI within the resizeEvent of the Popup_Window ;
corrected the method move_UI in Popup_Window so that the popup does not blink on and off to one location to the other ;
moved the eventFilter directly within the Popup_Window ;
merged the functions handling the events for the button.clicked.connect in Tool_Window.
The solution is not perfect, there is still a little 'flicker' of the popup window when it is expanding and moving in Ubuntu. This is not very apparent in Windows7 however. If I think of another solution, I'll do an update.
from PySide import QtCore, QtGui
import sys
class Tool_Window(QtGui.QDialog): #=============================================
def __init__(self, parent=None):
super(Tool_Window, self).__init__(parent)
self.create_gui()
self.create_layout()
self.create_connections()
def create_gui(self): #=====================================================
self.button1 = QtGui.QPushButton('Button 1')
self.button2 = QtGui.QPushButton('Button 2')
self.button3 = QtGui.QPushButton('Button 3')
def create_layout(self): #==================================================
layout = QtGui.QVBoxLayout()
layout.addWidget(self.button1)
layout.addWidget(self.button2)
layout.addWidget(self.button3)
self.setLayout(layout)
def create_connections(self): #=============================================
self.button1.clicked.connect(self.on_lef_click )
self.button2.clicked.connect(self.on_lef_click )
self.button3.clicked.connect(self.on_lef_click )
def on_lef_click(self): #===================================================
button = self.sender()
self.popup = Popup_Window(self, button)
self.popup.show()
class Popup_Window( QtGui.QWidget ): #==========================================
def __init__( self, parent, button):
super(Popup_Window, self ).__init__(parent)
self.setWindowFlags(QtCore.Qt.Popup)
self.button = button
self.parent = parent
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
#---- set layout key dimension ----
self.min_width = 100
self.frame_thick = 10
self.setFixedWidth(self.min_width)
#---- init GUI ----
self.installEventFilter(self)
self.create_gui()
self.create_layout()
self.create_connections()
self.move_UI()
self.line_edit.setFocus()
def create_gui( self ): #===================================================
self.my_label = QtGui.QLabel("default text")
self.my_label.setAlignment(QtCore.Qt.AlignRight)
self.line_edit = QtGui.QLineEdit()
self.line_edit.setAlignment(QtCore.Qt.AlignRight)
self.line_edit.setMaxLength( 50 )
def create_layout( self ): #================================================
button_layout = QtGui.QGridLayout()
button_layout.addWidget(self.my_label, 0, 0)
button_layout.addWidget(self.line_edit, 1, 0)
button_layout.setContentsMargins(self.frame_thick, self.frame_thick,
self.frame_thick, self.frame_thick)
self.setLayout(button_layout)
def create_connections(self): #=============================================
self.line_edit.textChanged.connect(self.line_edit_text_changed)
def line_edit_text_changed(self, text): #==================================
#---- set the text in label ----
self.my_label.setText(text)
#---- determine new width of popup ----
fm = self.line_edit.fontMetrics()
txtWidth = fm.boundingRect(text).width() + 10 # Padding to the left.
# Value is arbitrary.
newWidth = max(txtWidth + self.frame_thick * 2, self.min_width)
self.setFixedWidth(newWidth)
def eventFilter(self, source, event): #=====================================
if event.type() == QtCore.QEvent.WindowDeactivate:
self.close()
return QtGui.QWidget.eventFilter(self, source, event)
def resizeEvent(self, event): #=============================================
self.move_UI()
QtGui.QWidget.resizeEvent(self, event)
def move_UI(self): # =======================================================
y_btn = self.button.mapToGlobal(QtCore.QPoint(0, 0)).y()
x_win = self.parent.mapToGlobal(QtCore.QPoint(0, 0)).x()
w_pop = self.frameGeometry().width()
x = x_win - w_pop - 12 # 12 is an arbitrary value.
y = y_btn
self.move(QtCore.QPoint(x, y))
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
instance_1 = Tool_Window()
instance_1.show()
sys.exit(app.exec_())
This results in:
Update (2015-07-30): Popup shrink to the width of the content
I've extended the example so that now the popup starts with a minimum with of 100 that extends when the width of the text goes over this value. Also, the width of the popup will shrink, down to the minimum value of 100, if text is removed.
This is done by calculating the width of the text in QLineEdit when its content change and using the value to assign a fixed width to the popup window in the method line_edit_text_changed.

How to set a Gtk2::Button's text colour?

I am trying to set a colour to highlight a button. However, the modify_fg method only seems to set the focus ring's colour. modify_bg works as expected.
This is my code:
use Gtk2 qw/-init/;
my $window = Gtk2::Window->new;
$window->set_title("Window!");
my $button = Gtk2::Button->new("Coloured _button");
# does not affect text
$button->modify_fg(normal => Gtk2::Gdk::Color->new(0xffff, 0, 0));
$window->add($button);
$window->show_all;
Gtk2->main;
I'm also interested whether there is a standard colour for this sort of highlight, to blend in with the user's theme.
you can get the button's child label and modify its foreground, below is an example (python, let me know if there are troubles converting it to perl)
import gtk
class TestWindow:
def __init__(self):
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
box = gtk.VBox()
button0 = gtk.Button("Test Button")
label0 = button0.get_children()[0]
label0.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse('red'))
button1 = gtk.Button(stock=gtk.STOCK_ABOUT)
alignment = button1.get_children()[0]
hbox = alignment.get_children()[0]
image, label1 = hbox.get_children()
label1.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse('blue'))
box.add(button0)
box.add(button1)
window.add(box)
window.set_size_request(200, 200)
window.show_all()
def close_application(self, widget, event, data=None):
gtk.main_quit()
return False
if __name__ == "__main__":
TestWindow()
gtk.main()
hope this helps, regards
All previous helped a lot...
All the following works ok!
my $beige = Gtk2::Gdk::Color->new (0xFFFF,0xFFFF,0xCCCC);
my $azul = Gtk2::Gdk::Color->new (0,0,0xCCCC);
my $rojo = Gtk2::Gdk::Color->new (0xCCCC,0,0);
$mw->modify_bg ("normal", $beige);
my $butOk = Gtk2::Button->new_with_label(" 🗹 ¡Ya Terminé!");
($butOk->get_children)[0]->modify_fg("normal", $azul);
($butOk->get_children)[0]->modify_font(Pango::FontDescription->from_string ("Serif Bold 27"));
my $imgBTN = Gtk2::Button->new();
my $img = Gtk2::Image->new_from_file("$imagen");
$imgBTN->set_property("image"=>$img);