Why doesn't this Python 2.7 Turtle code process penup? - python-2.7

Below is my code (it doesn't process the penup). What's wrong with this code? (Sorry about my bad English.)
import turtle
import time
t = turtle.Turtle()
wn = turtle.Screen()
t.ht()
t.pensize(6)
t.speed(0)
wn.title("Trivia")
class trivia():
def __init__(self):
self.BlueBtn()
def Btn(self):
t.begin_fill()
for p in xrange(2):
t.left(90)
t.fd(170)
t.lt(90)
t.fd(470)
t.end_fill()
def BlueBtn(self): #button a - the blue button
t.penup()
t.setx(-370)
t.pendown()
t.color("blue","aqua") #make the button's color
self.Btn() #make the button
self.RedBtn()
def RedBtn(self): #button b - the red button
t.pu()
t.setx(370)
t.pd()
t.color("darkred","red") #make the button's color
self.Btn()
self.GreenBtn()
def GrennBtn(self): #button c - the green button
t.pu()
t.sety(-400)
t.pd()
t.color("darkgreen","green") #make the button's color
self.Btn(self) #make the button
self.GoldBtn()
def GoldBtn(self): #make button d - the gold button
t.pu()
t.setx(-370)
t.pd()
t.color("gold","khaki") #make the button's color
self.Btn() #make the button
turtle.mainloop() #exit from the turtle screen while pressing on the cross
game = trivia()

The major problem with this code is this sequence:
turtle.mainloop()
game = trivia()
When you invoke mainloop() you turn control over to the Tk event loop so it should be the last thing you do. Commands after this don't get executed until turtle is being shut down. So reverse it:
game = trivia()
turtle.mainloop()
There are also lots of little errors (e.g. self.Btn(self) passes two self arguments instead of one) which I've tried to address in a rewrite of your code that should run under Python 2 or 3:
from turtle import Turtle, Screen, mainloop
class trivia():
def __init__(self):
self.BlueBtn((-550, 100))
self.RedBtn((100, 100))
self.GreenBtn((100, -250))
self.GoldBtn((-550, -250))
def Btn(self, position):
turtle.penup()
turtle.setposition(position)
turtle.pendown()
turtle.begin_fill()
for _ in range(2):
turtle.forward(450)
turtle.left(90)
turtle.forward(150)
turtle.left(90)
turtle.end_fill()
def BlueBtn(self, position): # button a - the blue button
turtle.color('blue', 'cyan') # I don't have 'aqua'
self.Btn(position)
def RedBtn(self, position): # button b - the red button
turtle.color('darkred', 'red')
self.Btn(position)
def GreenBtn(self, position): # button c - the green button
turtle.color('darkgreen', 'green')
self.Btn(position)
def GoldBtn(self, position): # make button d - the gold button
turtle.color('gold', 'khaki')
self.Btn(position)
screen = Screen()
screen.setup(1200, 600)
screen.title('Trivia')
turtle = Turtle(visible=False)
turtle.speed('fastest')
turtle.pensize(6)
game = trivia()
mainloop() # exit from the turtle screen by pressing on the cross

Related

Tkinter windows decoration

I am using Tkinter for Building GUI for my python module but i don't want default windows title bar and border. I used "root.overrideredirect(True)" but with "overrideredirect()" I am losing control from my window like resizing and shifting from one place to another place. When ever I run my GUI its shows on top-left corner of my window.
from Tkinter import *
version = "v0.1"
def getinfo():
lab1 = Label(fram, text = "Your name :")
lab2 = Label(fram, text = "Your Password : ")
lab1.grid(row =1,sticky=W)
lab2.grid(row =2,sticky=W)
def Exit():
sys.exit(1)
def btn2():
btn_show = Button(fram,text = "Show")
btn_show.grid(row = 9, sticky = W)
btn_hide = Button(fram, text = "Hide")
btn_hide.grid(row = 9,column = 2, sticky = W)
root = Tk()
root.overrideredirect(True)
root.geometry("450x300")
fram = Frame(root)
fram.grid()
default_labels()
btn2()
root.mainloop()
Here is a basic example of how you can build your title bar and be able to move your window around. It is not perfect but should serve as a good starting point for your.
import Tkinter as tk
root = tk.Tk()
root.overrideredirect(True)
root.geometry("450x300")
root.config(background="darkblue")
root.columnconfigure(0, weight=1)
def move_event(event):
root.geometry('+{0}+{1}'.format(event.x_root, event.y_root))
title_frame = tk.Frame(root)
title_frame.grid(row=0, column=0, sticky="ew")
title_frame.columnconfigure(0, weight=1)
title_frame.bind('<B1-Motion>', move_event)
tk.Label(title_frame, text="Custom title bar").grid(row=0, column=0, sticky="w")
tk.Button(title_frame, text="-").grid(row=0, column=1, sticky="e")
tk.Button(title_frame, text="[]").grid(row=0, column=2, sticky="e")
tk.Button(title_frame, text="X", command=root.destroy).grid(row=0, column=3, sticky="e")
tk.Label(root, text="Test window!", fg="white", bg="darkblue").grid(row=1, column=0)
root.mainloop()
Results:
The resulting window can be dragged around though a little bit off as the window will want to move relative to the mouse position.
Yes, that's exactly what overrideredirect does. You will have to add your own bindings to allow for interactively moving and resizing the window.
The answer to the question Tkinter: windows without title bar but resizable shows how to add resizing.
The answer to the question Python/Tkinter: Mouse drag a window without borders, eg. overridedirect(1) shows how to handle the moving of the window.

pygame my picture wont show up on my window

import pygame
import sys
import os
from pygame.locals import *
#Allows for the editing of a window
pygame.init()
#Sets screen size
window = pygame.display.set_mode((800,600),0,32)
#Names the window
pygame.display.set_caption("TEST")
#Types of colors (red,green,blue)
black = (0,0,0)
blue = (0,0,255)
green = (0,255,0)
yellow = (255,255,0)
red = (255,0,0)
purple = (255,0,255)
lightblue = (0,255,255)
white = (255,255,255)
pink = (255,125,125)
mif="climb.PNG"
mif=pygame.image.load(mif).convert()
#Loop
gameLoop = True
while gameLoop:
pygame.display.flip() #must flip the image o the color is visable
window.blit(mif, (0,0))
window.fill(black) #used to fill the creen with the certian color variables
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameLoop=False #Allows the user to exit the loop/game
pygame.quit() #quit the pygame interface
exit(0)
When I select run my yellow window pops up but no image...
I'm new to pygame and python so maybe I just did something wrong?
Is there a specific place that I should have my image saved to?
I'm running on a windows 8 hp ENVY...
I just want to learn what I'm doing wrong so I don't make the error again. (I should also add that I have tried many different pictures and some where not able to be located.)
First fill window with black color window.fill(black),
then put image on it window.blit(mif, (0,0)),
and last send it to your graphic card (and on your monitor) pygame.display.flip()
window.fill(black)
window.blit(mif, (0,0))
pygame.display.flip()
If your image is as big as window then you don't need to use fill(black).
You can keep image in the same folder with script. Or you can create subfolder only for image to have order in folders.
If you call this folder images then you have to add this to filenames images/climb.PNG.
BTW: better use / than \ in path because \n in path can be interpreted as ENTER/new line as in any text.
But the most properly is:
import os
filename = os.path.join('images', 'climb.PNG')

Getting the text of label once button is clicked (Tkinter)

I am new to Python and Tkinter so I am trying to create a sample program to explore.
The program basically shows the names as a Label then 4 buttons will be put right next to the Label.
One of the buttons is "Delete" and what I want to do is, the button will get the name of the Label that is right next to that 'Delete" button.
The code is :
from Tkinter import *
class GUI():
def __init__(self):
self.namelist = ["Mark","Anna","Jason","Lenna",
"Leo","Zucharich","Robinson",
"AReallyLongNameThatMightExist"]
self.canvas = Canvas(width=1200,height=700)
self.canvas.pack(expand=YES,fill=BOTH)
def Friends(self):
frame = Frame(self.canvas)
frame.place(x=600,y=300)
#Frame for showing names of friends
row = 0
for x in self.namelist:
label = Label(frame,text="%s "%x)
chatButton = Button(frame,text="Chat")
delButton = Button(frame,text="Delete")
setcloseButton = Button(frame,text="Set Close")
setgroupButton = Button(frame,text="Set Group")
label.grid(row=row, column=0, sticky="W")
chatButton.grid(row=row, column=1)
delButton.grid(row=row, column=2)
setcloseButton.grid(row=row, column=3)
setgroupButton.grid(row=row, column=4)
row = row + 1
mainloop()
GUI = GUI()
GUI.Friends()
Example: If you run the code, then when you click "Delete" button next to "Mark", then the button will return "Mark".
Thanks!
Tk buttons have a command option to allow you to specify code to be run when the button is clicked. In this case you just want to pass the sibling widget name to your function. You can do this by capturing the widget name at creation time:
label = ...
delButton = Button(frame,text="Delete",
command=self.makeClosure(label))
...
def makeClosure(self, labelWidget):
return lambda: self.onClick(labelWidget)
def onClick(self, labelWidget):
print(labelWidget["text"])
In this example, when we create the delButton widget, the command is defined as a lambda that creates a closure including the label variable as it is defined at the time when this lambda is defined. Now when the delButton is clicked, this value will be passed to the onClick function which can use this to call methods on the widget at runtime.

multiple tasks on tkinter canvas?

I am trying to update canvas background at the same time running a binding event.
(from code)In do_popup popup menu will be implemented and conti will continuously change the canvas background color. how can i use popup option while canvas is updating continuously.
Sample code:
from Tkinter import *
root = Tk()
def do_popup(event,w2):
print w2 # inplace of print some popupmenu will be implemented
def conti():
idt=1
while idt==1:
w.config(bg="red") # in place of red it will be a random color
w.update_idletasks()
w= Canvas(root, width=600, height=600)
w.grid(row=0, column=0)
line1 = w.create_line(200,200,300,300, width=10, tags="line1", fill="black")
w.tag_bind(line1, "<Button-3>", lambda e, w2="test1" :do_popup(e,w2))
f = Frame(root)
f.grid(row=0, column=1, sticky=N)
f1=Button(f, text='visual', command=lambda :conti())
f1.grid(row=0, column=1,columnspan=1, sticky=W+N+S+E)
mainloop()
will multiprocessing work?
I am using windows 7 32 bit with python 2.7.3
Thanks in advance
When your script enters the mainloop then the events are executed.
To make reoccurring updates I like to do this:
def conti():
try:
w.config(bg="red") # in place of red it will be a random color
finally:
# start conti after 10 milliseconds,
root.after(10, conti)
# could also be 0ms to handle events
root.after(0, conti)
You can see root.mainloop as
while not (root.quit was called):
root.update()
This way wou can do:
root.quit()
and conti automatically stops.
There is no concurrency as with threads in mainloops.
But you can put a mainloop() somewhere when you create an own dialog box and conti will go on.
If you use the modules tkMessageBox(Python2) or tkinter.messagebox(Python3) then you conti should run while the dialog is open.
Does this answer your questions?
PS: do root.protocol("WM_DELETE_WINDOW", root.quit) to make the mainloop end when you close the window.

How do I wait for a certain number of buttons to be clicked in Tkinter/Python?

I'm trying to write a simple 'Simon' game, but I have hit a road block here, and honestly have no idea how to get around it.
So here, I made a class for the four buttons in the GUI:
class button:
def buttonclicked(self):
self.butclicked= True
def checkIfClicked(self):
if self.butclicked== True:
global pressed
pressed.append(self.color)
self.butclicked= False
def __init__(self, color1):
self.color= color1
self.button= tk.Button(root, text=' '*10, bg= self.color, command= self.buttonclicked)
self.button.pack(side='left')
self.butclicked=False
I then created four instances of this class in blue, red, yellow, and green as bb, rb, yb, and gb.
Once everything is packed into the Tk() module, it enters a while loop that appends a random color to a list activecolors. I try to use the following loop to wait until the list pressed is at least as long as the list activecolors before comparing the two to see if the user was correct:
while len(pressed)<len(activecolors):
sleep(.25)
print('In the check loop')
bb.checkIfClicked()
rb.checkIfClicked()
yb.checkIfClicked()
gb.checkIfClicked()
However, since it is stuck inside the while loop, the program can't tell that the button has been clicked. I thought adding the sleep method into the loop would allow the code to have time to do other things (such as process button clicks), but this is not the case. Any help is appreciated.
Here is the link to the full code, if you would like to see it. A warning though: it's not pretty.
Edit:
I ended up just changing the code to check the list only after a new button was clicked, telling the computer the code was ready. I've updated the Google Document if you'd like to see it.
You are making it too complicated. This program uses partial from functiontools to allow a variable to be passed to the function so one function handles all clicks (Python 2.7).
from Tkinter import *
from functools import partial
class ButtonsTest:
def __init__(self):
self.top = Tk()
self.top.title('Buttons Test')
self.top_frame = Frame(self.top, width =400, height=400)
self.colors = ("red", "green", "blue", "yellow")
self.colors_selected = []
self.num_clicks = 0
self.wait_for_number = 5
self.buttons()
self.top_frame.grid(row=0, column=1)
Button(self.top_frame, text='Exit',
command=self.top.quit).grid(row=2,column=1, columnspan=5)
self.top.mainloop()
##-------------------------------------------------------------------
def buttons(self):
for but_num in range(4):
b = Button(self.top_frame, text = str(but_num+1),
command=partial(self.cb_handler, but_num))
b.grid(row=1, column=but_num+1)
##----------------------------------------------------------------
def cb_handler( self, cb_number ):
print "\ncb_handler", cb_number
self.num_clicks += 1
this_color = self.colors[cb_number]
if (self.num_clicks > self.wait_for_number) \
and (this_color in self.colors_selected):
print "%s already selected" % (this_color)
self.colors_selected.append(this_color)
##===================================================================
BT=ButtonsTest()