How to make the keyboard work as a touchscreen in Python? - python

If LtRt() executed 1st UpDown() doesnt work and vice-versa. What should I do? Also please help me optimize the code.
I play games from an app that doesnt support to login via Android emulator like Bluestacks etc. Because they autofill the security code, which emulators cant fill. In PC I can't play these games with the mouse as I need fingers touch (better flexibility)
Is it possible to make my keyboard work like fingers on a touchscreen on PC?
For example:
'w' = front
'q' = top left corner
'e' = top right corner
'a' = left
's' = presses or at center
'd' = right
'z' = bottom left corner
'x' = back
'c' = bottom right corner
Is there any way to directly command Windows to make 9 points and tap?
And if s+d are pressed give a swipe to the right (as if with a finger) and so on?
import win32api
from time import sleep
import keyboard as kb
import sys
import pyautogui as pg
def UpDown():
py = (win32api.GetCursorPos())[1]
y = py
while True:
px = (win32api.GetCursorPos())[0]
x = px
#TOP
if kb.is_pressed('w'):
# win32api.SetCursorPos((y,574))
pg.moveTo(x, y, duration=0.0)
y = y - 40
#BOTTOM
if kb.is_pressed('s'):
# win32api.SetCursorPos((y,574))
pg.moveTo(x, y, duration=0.0)
y = y + 40
# Y = NEW POSITION; ON RELEASE
if not kb.is_pressed('w') and not kb.is_pressed('s'):
y = (win32api.GetCursorPos())[1]
def LtRt():
px = (win32api.GetCursorPos())[0]
x = px
while True:
py = (win32api.GetCursorPos())[1]
y = py
# X = NEW POSITION; ON RELEASE
if not kb.is_pressed('a') and not kb.is_pressed('d'):
x = (win32api.GetCursorPos())[0]
#LEFT
if kb.is_pressed('a'):
# win32api.SetCursorPos((y,574))
pg.moveTo(x, y, duration=0.0)
x = x - 60
#RIGHT
if kb.is_pressed('d'):
# win32api.SetCursorPos((y,574))
pg.moveTo(x, y, duration=0.0)
x = x + 60
if __name__ == "__main__":
LtRt()
UpDown()
while kb.is_pressed('q'):
break

I somehow managed an answer of my own problem (^_^)!
called the same function win32api.GetCursorPos() in 2 way and called them in 2 way.
But Someone to help me with an OPTIMIZED version of this. Thanks in Advance from all who will be getting help from this in future...
import win32api
from time import sleep
import keyboard as kb
import sys
import pyautogui as pg
def UpDown():
#UpDown > qy
qy = (win32api.GetCursorPos())[1]
y = qy
#LtRt > x1 y1
px = (win32api.GetCursorPos())[0]
x1 = px
while True:
#UpDown
px = (win32api.GetCursorPos())[0]
x = px
#LtRt
py = (win32api.GetCursorPos())[1]
y1 = py
#TOP
if kb.is_pressed('w'):
# win32api.SetCursorPos((y,574))
pg.moveTo(x, y, duration=0.0)
y = y - 40
#BOTTOM
if kb.is_pressed('s'):
# win32api.SetCursorPos((y,574))
pg.moveTo(x, y, duration=0.0)
y = y + 40
# Y = NEW POSITION; ON RELEASE
if not kb.is_pressed('w') and not kb.is_pressed('s'):
y = (win32api.GetCursorPos())[1]
# X = NEW POSITION; ON RELEASE
if not kb.is_pressed('a') and not kb.is_pressed('d'):
x1 = (win32api.GetCursorPos())[0]
#LEFT
if kb.is_pressed('a'):
# win32api.SetCursorPos((y,574))
pg.moveTo(x1, y1, duration=0.0)
x1 = x1 - 60
#RIGHT
if kb.is_pressed('d'):
# win32api.SetCursorPos((y,574))
pg.moveTo(x1, y1, duration=0.0)
x1 = x1 + 60
if kb.is_pressed('q'):
break
UpDown()

Related

Can I set an exact location of an object using tkinter?

Using Python3.7 I have created code that will move a ball from the top left corner to the bottom right corner. I am using coords to position the ball and move for the motion of the ball. However, I want the ball to start in a certin place. How can I set the position of the ball?
I have tried using place function and I get the error: 'int' object has no attribute 'place'
I tried using coords and I get the error: IndexError: list index out of range
I have tried changing my create_oval code. It works for the size of the ball but not where it starts from.
The code here works with no errors. How and where should I have a line for the exact coordinates of where the ball will start.
import tkinter as tkr
import time
tk = tkr.Tk()
canvas = tkr.Canvas(tk, width=480, height=480)
canvas.grid()
ball = canvas.create_oval(10,10,20,20,fill="blue")
x = 1
y = 1
while True:
canvas.move(ball,x,y)
pos = canvas.coords(ball)
if pos [3] >= 480 or pos[1] <=0:
y = -y
if pos[2] >= 480 or pos[0] <= 0:
x = -x
tk.update()
time.sleep(0.0099)
pass
tk.mainloop()
Also if I can get rid of the deprecation warning, that would be great as well.
Here's how you do a loop like this within the confines of an event-driven UI framework. Each callback does one little bit of work, then goes back to the loop to wait for future events.
import tkinter as tk
import time
win = tk.Tk()
canvas = tk.Canvas(win, width=480, height=480)
canvas.grid()
x = 10
y = 10
dx = 1
dy = 1
def moveball():
global x, dx
global y, dy
x += dx
y += dy
canvas.move(ball,dx,dy)
if y >= 480 or y <=0:
dy = -dy
if x >= 480 or x <= 0:
dx = -dx
win.after( 10, moveball )
ball = canvas.create_oval(x,y,x+10,y+10,fill="blue")
win.after( 100, moveball )
win.mainloop()
You'll note that the ball doesn't change directions until after it's all the way off the edge of the screen. That's because we're tracking the upper left corner of the ball and not taking the size into account. That's an easy thing to fix.
Used variables with the create_oval.
import tkinter as tkr
import time
tk = tkr.Tk()
canvas = tkr.Canvas(tk, width=480, height=480)
canvas.grid()
x = 47
y = 185
ball = canvas.create_oval(x,y,x+10,y+10,fill="blue")
dx = 1
dy = 1
while True:
canvas.move(ball,dx,dy)
pos = canvas.coords(ball)
if pos [3] >= 480 or pos[1] <=0:
dy = -dy
if pos[2] >= 480 or pos[0] <= 0:
dx = -dx
tk.update()
time.sleep(0.0099)
pass
tk.mainloop()
Big thanks to Tim Roberts. I end up taking his coding advice and edit mine original code.

How to show this message when mouse stop

I want use python3 (tkinter) to finish this function:
When the mouse stop at some place, one message will be shown.
When the mouse move away, the message will disappear.
Is there any information for this function?
This effect can be achieved by combining bind and after.
The motion of cursor is tracked with bind which removes label
after checks every 50 milliseconds for non-movement of cursor and uses place manager to display label.
I've updated answer since bind event.x and y caused an occasional bug in the positioning of the message. (displaying it at top left corner)
Tracked it down to event.x event.y, so replaced it with
x = root.winfo_pointerx() - root.winfo_rootx()
y = root.winfo_pointery() - root.winfo_rooty()
This update solves the problem, now it functions as intended.
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text = "Message")
x = y = xx = yy = 0
def display(event):
global x, y
x = root.winfo_pointerx() - root.winfo_rootx()
y = root.winfo_pointery() - root.winfo_rooty()
label.place_forget()
def check(xx, yy):
global x, y
if x == xx and y == yy:
label.place(x = x, y = y, anchor = "s")
else:
xx, yy = x, y
root.after(50, check, xx, yy)
root.bind("<Motion>", display)
root.after(10, check, xx, yy)
root.mainloop()

Trouble identifying when user clicks inside circle with Zelle graphics

I am creating a program in Python using Zelle graphics package. There is a moving circle that the user clicks on in order to make it return to the center of the screen. I cannot figure out how to identify when the user clicks inside of the circle. Here is the code I have written:
from graphics import *
from time import sleep
import random
Screen = GraphWin("BallFalling", 400 , 400);
Screen.setBackground('green')
ball = Circle(Point(200,200),25);
ball.draw(Screen);
ball.setFill('white')
ballRadius = ball.getRadius()
ballCenter = 0
directionX = (random.random()*40)-20;
directionY = (random.random()*40)-20;
clickx = Screen.getMouse().getX();
clicky = 0
while ball.getCenter().getX() + ball.getRadius() <= 400 and ball.getCenter().getY() + ball.getRadius() <= 400 and ball.getCenter().getX() >= 0 and ball.getCenter().getY() >= 0:
ball.move(ball.getRadius()//directionX,ball.getRadius()//directionY)
ballLocation = ball.getCenter().getX();
ballLocationy = ball.getCenter().getY();
sleep(1/15);
The main problem I am having is identifying the coordinates of the mouse click. I cannot find anything in the Zelle graphics package that says anything about this.
The major issues I see are: you are calling getMouse() before the loop when you should be calling checkMouse() inside the loop; you have no code to compare the distance of the click from the ball; you have no code to return the ball to the center of the screen.
Below is my complete rework of your code addressing the above issues:
from time import sleep
from random import randrange
from graphics import *
WIDTH, HEIGHT = 400, 400
RADIUS = 25
def distance(graphic, point):
x1, y1 = graphic.getCenter().getX(), graphic.getCenter().getY()
x2, y2 = point.getX(), point.getY()
return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
window = GraphWin("Ball Falling", WIDTH, HEIGHT)
window.setBackground('green')
ball = Circle(Point(WIDTH/2, HEIGHT/2), RADIUS)
ball.setFill('white')
ball.draw(window)
directionX = randrange(-4, 4)
directionY = randrange(-4, 4)
while True:
center = ball.getCenter()
x, y = center.getX(), center.getY()
if not (RADIUS < x < WIDTH - RADIUS and RADIUS < y < HEIGHT - RADIUS):
break
point = window.checkMouse()
if point and distance(ball, point) <= RADIUS:
ball.move(WIDTH/2 - x, HEIGHT/2 - y) # recenter
directionX = randrange(-4, 4)
directionY = randrange(-4, 4)
else:
ball.move(directionX, directionY)
sleep(1/30)
There may still be subtle bugs and contants tweaking for you to sort out.

How to get the position of the point in Vispy 3d plot?

I am beginner of the VisPy.
All I want to do is:
Click the point then this point will change color and print the position (x,y,z) of this point.
But I can't find how to do this.
Here is my code.
import numpy as np
import sys
from vispy import app, visuals, scene
class Canvas(scene.SceneCanvas):
""" A simple test canvas for testing the EditLineVisual """
def __init__(self):
scene.SceneCanvas.__init__(self, keys='interactive',
size=(800, 800), show=True)
# # Create some initial points
self.unfreeze()
# Add a ViewBox to let the user zoom/rotate
self.view = self.central_widget.add_view()
self.view.camera = 'turntable'
self.view.camera.fov = 30
self.show()
self.selected_point = None
scene.visuals.GridLines(parent=self.view.scene)
self.freeze()
def on_mouse_press(self, event):
print(event.pos) # How to convert this pos to canvas position??
Scatter3D = scene.visuals.create_visual_node(visuals.MarkersVisual)
canvas = Canvas()
p1 = Scatter3D(parent=canvas.view.scene)
p1.set_gl_state('translucent', blend=True, depth_test=True)
# fake data
x = np.random.rand(100) * 10
y = np.random.rand(100) * 10
z = np.random.rand(100) * 10
# Draw it
point_list = [x, y, z]
point = np.array(point_list).transpose()
p1.set_data(point, symbol='o', size=6, edge_width=0.5, edge_color='blue')
if __name__ == "__main__":
if sys.flags.interactive != 1:
app.run()
I just had the same problem. I solved it by using the following code, hope this helps.
def on_mouse_press(self, event):
#1=left, 2=right , 3=middle button
if event.button == 1:
p2 = event.pos
norm = np.mean(self.view.camera._viewbox.size)
if self.view.camera._event_value is None or len(self.view.camera._event_value) == 2:
ev_val = self.view.camera.center
else:
ev_val = self.view.camera._event_value
dist = p2 / norm * self.view.camera._scale_factor
dist[1] *= -1
# Black magic part 1: turn 2D into 3D translations
dx, dy, dz = self.view.camera._dist_to_trans(dist)
# Black magic part 2: take up-vector and flipping into account
ff = self.view.camera._flip_factors
up, forward, right = self.view.camera._get_dim_vectors()
dx, dy, dz = right * dx + forward * dy + up * dz
dx, dy, dz = ff[0] * dx, ff[1] * dy, dz * ff[2]
c = ev_val
#shift by scale_factor half
sc_half = self.view.camera._scale_factor/2
point = c[0] + dx-sc_half, c[1] + dy-sc_half, c[2] + dz+sc_half
print("final point:", point[0], point[1], point[2])

Trouble drawing Bezier Curve

Im trying to graph a cubic bezier curve however, I am having difficulty with the last part of the program. I cant seem to get tkinter to actually draw the curve. It will currently just draw a small line in the top left of the tkinter window and im not sure if im doing it the wrong way or not.
from tkinter import *
root = Tk()
window = Canvas(root, width=800, height=800)
window.pack()
def bezier_curve():
#create empty list for points
p = []
#loops through 4 times to get 4 control points
for i in range(4):
while True:
#user input
p_input = input("Enter X,Y Coordinates for p" + str(i) + ":")
#splits the string into x and y coordinates
p_components = p_input.split(',')
#checks to see if user hasnt entered two coordinates
if len(p_components) != 2:
print("Missing coordinate please try again.")
p_input = input("Enter starting point X,Y Coordinates:")
#checks to see if the values can not be converted into floats.
try:
x = float(p_components[0])
y = float(p_components[1])
except ValueError:
print("Invalid coordinates", p_components, "please try again.")
#appends the x and y coordinates as a 2 dimensional array.
else:
p.append([float(p_components[0]), float(p_components[1])])
break
print(p[0][0])
#Start x and y coordinates, when t = 0
x_start = p[0][0]
y_start = p[0][1]
#loops through in intervals of 0.1
for t in range(0, 11, 1):
t = i/10
x=(p[0][0]*(1-t)**3+p[1][0]*3*t*(1-t)**2+p[2][0]*3*t**2*(1-t)+p[3][0]*t**3)
y=(p[0][1]*(1-t)**3+p[1][1]*3*t*(1-t)**2+p[2][1]*3*t**2*(1-t)+p[3][1]*t**3)
draw_line = window.create_line(x,y,x_start,y_start)
#updates initial values
x_start = x
y_start = y
bezier_curve()
root.mainloop()
Yes; a small error in the loop for drawing the lines:
#loops through in intervals of 0.1
for t in range(0, 11, 1):
t = i/10
You have assigned t as the loop variable when it should be i.
for t in range(0, 11, 1):
^
This shoud be i
#figbeam answer is correct, and fixes your problem.
I found your input mechanism tedious, so I changed it to allow clicks on the canvas to capture the control points of your bezier curve.
import tkinter as tk
def draw_bezier():
# Start x and y coordinates, when t = 0
x_start = control_points[0][0]
y_start = control_points[0][1]
p = control_points
# loops through
n = 50
for i in range(50):
t = i / n
x = (p[0][0] * (1-t)**3 + p[1][0] * 3 * t * (1-t)**2 + p[2][0] * 3 * t**2 * (1-t) + p[3][0] * t**3)
y = (p[0][1] * (1-t)**3 + p[1][1] * 3 * t * (1-t)**2 + p[2][1] * 3 * t**2 * (1-t) + p[3][1] * t**3)
canvas.create_line(x, y, x_start, y_start)
# updates initial values
x_start = x
y_start = y
def get_point(event):
global control_points
point = x, y = (event.x, event.y)
control_points.append(point)
canvas.create_oval(x, y, x+3, y+3)
if len(control_points) == 4:
draw_bezier()
control_points = []
if __name__ == '__main__':
control_points = []
root = tk.Tk()
canvas = tk.Canvas(root, width=800, height=800)
canvas.pack()
canvas.bind('<Button-1>', get_point)
root.mainloop()

Categories

Resources