I've been trying to make the Snake game using the Turtle module in Python3.
I want the program to close when the Esc key is pressed twice. Here's what i've tried so far, but I can't seem to get it working (i've previously imported the sys module):
def exitprogram():
sys.exit()
def close():
close = turtle.Turtle()
close.speed(0)
close.color("white")
close.penup()
close.hideturtle()
close.goto(0,0)
close.write("Press ESC again to exit", align="center", font = ("Courier", 24, "normal"))
window.listen()
window.onkeypress(exitprogram, "Escape")
window.listen()
window.onkeypress(close, "Escape")
window.mainloop()
Any help would be greatly appreciated!!
EDIT
Instead of using sys.exit(), i used window.bye() and that seemed to work just fine. Thanks!
Code works for me if I add mainloop() which gets key/mouse events from system and sends to turtle's window. You can also use window.bye() to exit mainloop()
import turtle
def exitprogram():
window.bye()
def close():
close = turtle.Turtle()
close.speed(0)
#close.color("white")
close.penup()
close.hideturtle()
close.goto(0,0)
close.write("Press ESC again to exit", align="center", font = ("Courier", 24, "normal"))
window.listen()
window.onkeypress(exitprogram, "Escape")
window = turtle.Screen()
window.listen()
window.onkeypress(close, "Escape")
window.mainloop()
I generally agree with #furas (+1) but I would go simpler as some methods you invoke are effectively no-ops in the context in which they are used:
from turtle import Screen, Turtle
def close():
window.onkeypress(window.bye, "Escape")
close = Turtle()
close.hideturtle()
# close.color("white")
close.write("Press ESC again to exit", align="center", font=("Courier", 24, "normal"))
window = Screen()
window.onkeypress(close, "Escape")
window.listen()
window.mainloop()
Related
I want to draw my turtle using arrow keys. And there's an option to change turtle pensize.
Here's my code:
from tkinter import *
from turtle import *
def ask():
someinputs = numinput('Test', 'Input size:', default=1, minval=0, maxval=999)
pensize(someinputs)
root = Tk()
Label(root, text='Settings:\n').pack()
Button(root, text='Pensize', command=ask).pack()
Label(root, text=' ').pack()
def up():
#anything here
fd(100)
def down():
#anything here
bk(100)
def left():
#anything here
lt(90)
fd(100)
def right():
#anything here
rt(90)
fd(100)
onkey(up, 'Up')
onkey(down, 'Down')
onkey(left, 'Left')
onkey(right, 'Right')
listen()
mainloop()
But after clicking the tkinter button to set the pensize, I can't use arrow keys to control anymore.
Can anyone help me, please? Also this doesn't work with turtle.textinput() too!
When you use the settings window, you take focus from the turtle window. The key events will only work when the turtle window has focus. Adapting this answer it is possible to get the underlying canvas and focus it by adding Screen().getcanvas().focus_force() to the end of ask:
def ask():
someinputs = numinput('Test', 'Input size:', default=1, minval=0, maxval=999)
pensize(someinputs)
Screen().getcanvas().focus_force()
Can you not add the listen method at the end of the ask function?
def ask():
someinputs = numinput('Test', 'Input size:', default=1, minval=0, maxval=999)
pensize(someinputs)
listen()
I am making a calculator with turtle-graphics. I want the turtle to type something when I press a button. The code is below:
import turtle
wn = turtle.Screen()
wn.title("rob it")
wn.bgcolor("black")
wn.setup(width=500, height=600)
CURSOR_SIZE = 20
FONT_SIZE = 12
FONT = ('Arial', FONT_SIZE, 'bold')
button = turtle.Turtle()
button.hideturtle()
button.shape('circle')
button.fillcolor('red')
button.penup()
button.goto(150, 650)
button.write("Click me!", align='center', font='arial')
button.sety(150 + + FONT_SIZE)
button.onclick('type_0')
button.showturtle()
#I think that's where the error occurs
def type_0(x, y):
turtle.penup
turtle.color('white')
turtle.goto(150, 650)
turtle.pendown
turtle.write('hello!', font='arial', align='center')
turtle.hideturtle
while True:
wn.update()
But I am getting this error. I have tried everything and I cannot fix it. Any solutions? For some reason I am not able to call the type_0 function.
So I am typing this because I don't know what other details to add and I am new to python so I will appreciate any comment or help.
The following is an implementation which will work but not an optimal/elegant solution. Okay to start with. As you learn more you can make your code much more elegant. One of the way is to use a class with methods. Also, please note that x,y arguments are not used in your function.
import turtle
wn = turtle.Screen()
wn.title("rob it")
wn.bgcolor("black")
wn.setup(width=500, height=600)
CURSOR_SIZE = 20
FONT_SIZE = 12
FONT = ('Arial', FONT_SIZE, 'bold')
button = turtle.Turtle()
button.hideturtle()
button.shape('circle')
button.fillcolor('red')
button.penup()
button.goto(150, 650)
button.write("Click me!", align='center', font='arial')
button.sety(150 + + FONT_SIZE)
def type_0(x, y,turtle_in_fn=button ):
turtle_in_fn.penup
turtle_in_fn.color('white')
turtle_in_fn.goto(150, 150)
turtle_in_fn.pendown
turtle_in_fn.write('hello!', font='arial', align='center')
turtle_in_fn.hideturtle
# Note that type_0 is a function. type_0 should not be within single quotes ''
button.onclick(type_0)
button.showturtle()
while True:
wn.update()
I am making a hack for a game, and I want to start/stop the script with the F7 hotkey while the game is running at full screen. I've tried to use root.bind and pynput to do it, but none of them worked.
Here is my code:
hack_running = False
def hack():
if hack_running:
PressKeyPynput(0x02)
time.sleep(0.08)
ReleaseKeyPynput(0x02)
PressKeyPynput(0x11)
time.sleep(0.5)
ReleaseKeyPynput(0x11)
PressKeyPynput(0x1F)
time.sleep(0.6)
ReleaseKeyPynput(0x1F)
PressKeyPynput(0x02)
time.sleep(0.08)
ReleaseKeyPynput(0x02)
root.after(900000, hack)
def Start_stop():
global hack_running
if Startk['text'] == 'Start':
hack_running = True
hack()
Startk.config(text='Stop')
else:
hack_running = False
Startk.config(text='Start')
root = tk.Tk()
root.resizable(False, False)
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()
frame = tk.Frame(root, bg='black')
frame.place(relwidth=1, relheight=1)
Startk = tk.Button(frame, text='Start', font=("Calibri", 10), command=Start_stop)
Startk.pack(side='top', pady='50')
root.mainloop()
Pynput has an easy class which provide hotkey function called GlobalHotKeys.Reference here.
Unfortunately,if there is only python,I think it couldn't do more if you want to make it work in game.
Normally, there are also keyboard listener thread in game.When your python script work with your game together,they will cause conflict.And your python script couldn't work normally.(And game will always take some measures to prevent cheating.)
As far as I know,AutoHotkey script could work in game(at least it worked for me in the past).AutoHotkey Official document.On macOS,refer this
Try using pynput:
import pynput
def run():
print('f7') # your code
def press(key):
if key == pynput.keyboard.Key.f7:
run()
pynput.keyboard.Listener(on_press=press).run()
For keyboard combinations see this github issue.
Hope that's helpful!
I am trying to create a turtle based, text adventure game with an interactive GUI. But I ran into a problem. In the image attached, you will see a ">" and then after that, I would like the user to be able to type a command, and submit it to determine the path of a game. I am relatively new to python, so I am not familiar with external libraries or modules that could help with this.
import os
import turtle
#SCREEN
screen = turtle.Screen()
screen.bgcolor("black")
screen.title("Untitled Game")
#Box
box = turtle.Turtle()
box.color("white")
box.speed(0)
box.penup()
box.setposition(-500, -200)
box.pensize(5)
box.pendown()
box.fd(900)
#TEXT IN TEXT BOX
text = turtle.Turtle()
text.speed(0)
text.color("white")
text.penup()
text.setposition(-350, 300)
text.write("This is a test", False, align="left", font=("Helvetica", 25, "normal"))
text.hideturtle()
#TEXT ARROW
arrow = turtle.Turtle()
arrow.speed(0)
arrow.color("white")
arrow.penup()
arrow.setposition(-360, -300)
arrow.pendown()
arrow.pensize(4)
arrow.write(">", False, align="left", font=("Helvetica", 60, "normal"))
screen.mainloop()
What it looks like right now
I am trying to use graphics.py to write a user graphics interface. The problem is that how can I capture the right click event? It seems that the function getMouse() could just returns where the mouse was left-clicked as a Point object.
from graphics import *
def main():
win = GraphWin("My Circle", 100, 100)
c = Circle(Point(50,50), 10)
c.draw(win)
win.getMouse() # pause for click in window
win.close()
main()
I want to know how can I capture the right-click event in the window, thanks.
I would recommend you try TkInter for a python GUI.
Here is an example that detects a right click:
from Tkinter import *
def showPosEvent(event):
print 'Widget=%s X=%s Y=%s' % (event.widget, event.x, event.y)
def onRightClick(event):
print 'Got right mouse button click:',
showPosEvent(event)
tkroot = Tk()
labelfont = ('courier', 20, 'bold')
widget = Label(tkroot, text='Hello bind world')
widget.config(bg='red', font=labelfont)
widget.config(height=5, width=20)
widget.pack(expand=YES, fill=BOTH)
widget.bind('<Button-3>', onRightClick)
widget.focus()
tkroot.title('Click Me')
tkroot.mainloop()