Error using checkmouse - python-3.x

I'm trying to use checkmouse in order to undraw something from my window. When someone clicks the button it should undraw the text and write something else. I'm using checkMouse and getX() and getY() to do this but i keep receiving this error that states:
File "C:\Users\User\Documents\python\project2.py", line 71, in panel
if (clicknew.getX()>90 and clicknew.getX()<210) and (clicknew.getY()>35 and clicknew.getY() < 0):
AttributeError: 'NoneType' object has no attribute 'getX'
this code that i have done so far is as follows:
from graphics import *
#creating the game panel window
def panel():
#grey window, with coordinates flipped, with banners etc
win = GraphWin("Start Panel", 300,200)
win.setCoords(0,0,300,200)
win.setBackground("light grey")
#drawing the BoilerMazer banner with text
boilermazer = Rectangle(Point(0,200),Point(300,160))
boilermazer.setFill("white")
boilermazer.draw(win)
#text inside
banner1 = Text(Point(150,180),"BoilerMazer")
banner1.setStyle("bold")
banner1.setSize(20)
banner1.draw(win)
#initial game panel is going to have two buttons and a top scores object
#top score "screen"
toprec = Rectangle(Point(60,140),Point(240,50))
toprec.setFill("white")
toprec.draw(win)
#text inside toprec
topscores = Text(Point(150,130),"TOP SCORES")
topscores.setSize(8)
topscores.draw(win)
border = Text(Point(150,120),"======")
border.draw(win)
bigmac = Text(Point(150,110),"Big Mac 21")
bigmac.setSize(8)
bigmac.draw(win)
tt = Text(Point(150,90),"T.T 23")
tt.setSize(8)
tt.draw(win)
cshell = Text(Point(150,75),"C-Shell 25")
cshell.setSize(8)
cshell.draw(win)
macmac = Text(Point(150,55),"MacMac 27")
macmac.setSize(8)
macmac.draw(win)
#new player button that will eventually be clicked
new1 = Point(90,35)
new2 = Point(210,0)
newrec = Rectangle(new1,new2)
newrec.setFill("chartreuse2")
newrec.draw(win)
#new player button text
newplayer = Text(Point(150,18),"NEW PLAYER")
newplayer.draw(win)
#reset button
resetrec = Rectangle(Point(240,35),Point(300,0))
resetrec.setFill("red")
resetrec.draw(win)
#resettext
reset = Text(Point(270,18),"RESET")
reset.draw(win)
#secondary panel window is the game panel after they click new player
#set up points that we check between for the new player button first
#setting up the checkmouse
clicknew = win.checkMouse()
if (clicknew.getX()>90 and clicknew.getX()<210) and (clicknew.getY()>35 and clicknew.getY() < 0):
newplayer.undraw()
you can find the graphics window here:http://mcsp.wartburg.edu/zelle/python/graphics.py
I don't understand what I'm doing wrong, is there some other method that I'm supposed to be using? Thanks for your help

According to the docs, checkMouse() returns None if no mouse click has been detected priorly. So that seems to be the case.
You could put a loop around the call to checkMouse and keep checking if clicknew is not None and only in that case go on in your program. But maybe there's a better way...
UPDATE:
Example:
while True:
clicknew = win.getMouse()
if clicknew:
break
else:
time.sleep(0.1) # avoid busy waiting
# clicknew is set now => use it

Related

InlineKeyboardMarkup Telegram bot (pyTelegramBotAPI)

I am making a bot on pyTelegramBotAPI, I need to generate a list of buttons and write it into the keyboard (So that there are 5 buttons in a row). How should I do it? I have a code:
def start(message):
markup = types.InlineKeyboardMarkup()
buttons = []
for i in range(-12, 15):
if i < 0:
button = types.InlineKeyboardButton(f'{i}', callback_data=f'{i}')
elif i == 0:
button = types.InlineKeyboardButton(f'±{i}', callback_data=f'{i}')
else:
button = types.InlineKeyboardButton(f'+{i}', callback_data=f'{i}')
buttons.append(button)
if len(buttons) == 5:
# here i want to add buttons in a row
bot.send_message(message.chat.id, f'Здравствуйте, <b>{message.from_user.first_name}</b>. Для начала необходимо настроить часовой пояс. Выберите разницу во времени относительно UTC (Москва: "+3", Владивосток: "+10", Исландия: "+1")', parse_mode='html', reply_markup=markup)```
I can advise you to create a separate module responsible for keyboards.
example of modules
This way you can separate the logic of handlers from the logic of keyboards.
As torrua wrote earlier, you can use the keyboa (how to use keyboa) library.
or write the functions yourself to create keyboards and buttons in it.
What you need to know for this:
telebot.types.InlineKeyboardMarkup() # creates an empty keyboard.
telebot.type.InlineKeyboardButton() # creates a button for the keyboard created earlier.
.row() # determines the position of the buttons in the keyboard.
example of function to get keyboards
You can do it easy with keyboa:
from keyboa import Keyboa
def start():
buttons = []
for i in range(-12, 15):
if i < 0:
button = (f'{i}', i)
elif i == 0:
button = (f'±{i}', i)
else:
button = (f'+{i}', i)
buttons.append(button)
keyboard = Keyboa(items=buttons, items_in_row=5).keyboard
bot.send_message(message.chat.id, f'Здравствуйте, <b>{message.from_user.first_name}</b>. Для начала необходимо настроить часовой пояс. Выберите разницу во времени относительно UTC (Москва: "+3", Владивосток: "+10", Исландия: "+1")', parse_mode='html', reply_markup=keyboard)```

notimplementederror: can't perform this operation for unregistered loader type python : trying to convert py to .exe using cx_freeze

I'm trying to convert a pygame project to an executable and it works fine on launch but when I clicked the play button it produces this error and I'm not sure how to fix it would be obliged if anyone could help me
import cx_Freeze
executables = [cx_Freeze.Executable("Consumo V25.py")]
cx_Freeze.setup(
name = "Consumo",
options ={"build_exe": {"packages":["pygame",_init_.py],
"include_files":["Blowfish.png", "dojo.png", "Rice_fresh.png", "rottenapple.png", "rottenfish.png", "rottenrice.png", "gameover.png", "Apple .png", "Fish.png","sumo .png","character.png"]}},
executables = executables
)
Here is the button function that is in my source code:
def button(msg,x,y,w,h,c,action=None):#passes the parameters by value
mouse = pygame.mouse.get_pos()#this gets the postion of the mouse
click = pygame.mouse.get_pressed()#checks to see where the mouse has been clicked
pygame.draw.rect(gameDisplay, c,(x,y,w,h))#draws a rectangle with on the game display with the parameters given
if x+w > mouse[0] >x and y+h > mouse[1] > y:#checks to see if the mouse has been clicked anywhere in the button
if click[0] == 1 and action != None:#if the mouse has been clicked performed an action
action()
smallText = pygame.font.SysFont("comicsansMS",20)
textSurf , textRect = textObjects(msg ,smallText)
#sets the message of the button
textRect.center = ((x+(w/2),(y+(h/2))))#centers the text on screen
gameDisplay.blit(textSurf, textRect)#puts the button on screen with the
here is where I'm running the function:
def menuScreen():
screenOn = True
while screenOn ==True:
for event in pygame.event.get():
if event.type == pygame.QUIT:#allows user to quit the game
quit()
gameDisplay.blit(dojoBackDrop,(0,0))#sets the image to the size of the screen
button("Play Game",850,340,120,50,blue,gameLoop)#Puts theree button on the screen
button("Leaderboard",850,440,120,50,blue)
button("Quit game",850,540,120,50,blue,quitGame)
pygame.display.update()#updates the screen so things can appear on it
The full error is :
File "C:\Users\Jackj\AppData\Local\Programs\Python\Python36\lib\site-packages\pygame\pkgdata.py", line 50, in getResource
if resource_exists(pkgname, identifier):
File "C:\Users\Jackj\AppData\Local\Programs\Python\Python36\lib\site-packages\pkg_resources\__init__.py", line 1191, in resource_exists
return get_provider(package_or_requirement).has_resource(resource_name)
File "C:\Users\Jackj\AppData\Local\Programs\Python\Python36\lib\site-packages\pkg_resources\__init__.py", line 1459, in has_resource
return self._has(self._fn(self.module_path, resource_name))
File "C:\Users\Jackj\AppData\Local\Programs\Python\Python36\lib\site-packages\pkg_resources\__init__.py", line 1509, in _has
"Can't perform this operation for unregistered loader type"
NotImplementedError: Can't perform this operation for unregistered loader type
You could try to find out which resource is causing the exception by replacing the lines 50 to 51 of C:\Users\Jackj\AppData\Local\Programs\Python\Python36\lib\site-packages\pygame\pkgdata.py with:
try:
if resource_exists(pkgname, identifier):
return resource_stream(pkgname, identifier)
except Exception as e:
print(pkgname, identifier)
raise e

How to Call a Function with 'on_press' command inside same class using KIVY button

I'm trying to call a popup and the have the user input text. After hitting the save button inside my popup it updates a new widget.
I have almost everything working but I don't know how to properly call a function inside the same class.
I have two functions inside of my
'class Trackers(Screen):'
how can I make a button that 'on_press' command will trigger another function?
The line of code I need to be fixed is this:
okay = Button(text='Save', on_press=self.addit(str(text_input), num), on_release=pop.dismiss)
Thank you so much.
''''
def addWidget(self):
num = '0'
box = BoxLayout(orientation= 'vertical', padding=40, spacing=5)
pop = Popup(title='Tracker: details', content=box, size_hint=(None,None), size=(300,300))
text_input = TextInput(hint_text='Add Trackers', multiline=False,)
okay = Button(text='Save', on_press=self.addit(str(text_input), num), on_release=pop.dismiss)
box.add_widget(text_input)
box.add_widget(okay)
pop.open()
def addit(self, text_input, num, *args):
if text_input not in self.storage.keys():
self.ids.track.add_widget(Tracker(text=text_input, number=num, data=self.storage))
self.storage[text_input] = '0'
text_input = ''
self.saveData()
else:
box = BoxLayout(orientation= 'vertical', padding=40, spacing=5)
pop = Popup(title=f'Opps: "{text_input}" is already listed below', content=box, size_hint=(None,None), size=(300,180))
try_again = Button(text='Try Again', on_release=pop.dismiss)
box.add_widget(try_again)
pop.open()
''''

Pyqt4 MDI no clean mdiarea

I am new to PyQt, I am developing an application like MDI, I use the QDesigner to build the forms (I come from Visual Basic), so far so good, but it is costing me horrors to run the application well, when I close a window, erase everything, but the frame remains on the mdi-area, click on the x and close. I attach the code.
With this I knock at the window:
def ordentrabajo(self):
self.cot = FichaOrdenTrabajo()
subwindow = QtGui.QMdiSubWindow()
self.cot.mdiarea = self.ventana.mdiArea
subwindow.setWidget(self.cot)
subwindow.setGeometry(0, 0, 595, 490)
self.ventana.mdiArea.addSubWindow(subwindow)
subwindow.showventana = self.cot.show()
And within the FichaOrdenTrabajo I close with:
def closeEvent(self, QCloseEvent):
self.emit(QtCore.SIGNAL('cerrar'))
general.saveposic('ctrlordentrabajo', self.x(), self.y())
self.subwindow.close = self.cdeta.close()
self.cdeta.hide()
# del self.subwindow
self.subwindow = None
leaving the main window in this state:
The question is how to do so that when closing the mdi-area is clean?
Thank you

How to manually set the toggle state of wxpython platebutton

I am building an application using platebutton iin wxpython. The problem is that I am not able to manually SetState of the toogle buton. I used SetState(0) but it does not change the state of toggle button. Any help would be great. Thanks. Sample code:
self.infinity= platebutton.PlateButton(self._ribbon,wx.ID_NEW, bmp = wx.Bitmap('infinity.bmp'), pos = (0,0), size = (38,18), style= platebutton.PB_STYLE_NOBG |platebutton.PB_STYLE_TOGGLE)
def OnInfinityToggled(self,event):
if event.GetEventObject().IsPressed():
self.popupmenu = wx.Menu()
Session = self.popupmenu.Append(-1, "Session")
self.Bind(wx.EVT_MENU, self.SessionMenu, Session)
self.PopupMenu(self.popupmenu,(2,23))
else:
pass
def SessionMenu(self, event):
print 5
self.infinity.SetState(0)
self.infinity.Raise()
PLATE_NORMAL = 0
PLATE_PRESSED = 1
PLATE_HIGHLIGHT = 2
SetState(0) means set to normal.
Here's how I managed to toggle state:
btn._ToggleState()
btn._pressed = True
I had the same problem. Playing around I managed to resolve my problem with
button._SetState(ix)
button.Refresh()
where ix = your choice of state.

Resources