I have a problem with my project. I want my class Baustein to be a blueprint of an object I can place in my Display in the gui_backup.py. The program launches and everything works, but as I click the left button (button1) the same program opens again and now I have 2 programs going separately but I have no new Object in the Display created, just the old one which is being created in gui_backup in blue, but I want to create one in red with the class Baustein from Bauklotz_class.py. Here are my codes:
Bauklotz_class.py
from gui_backup import Display
class Baustein:
x1, y1, x2, y2 = 10,10,20,20
color = "red"
def __init__(self, x1, y1, x2, y2, color):
self.x1 = x1
self.x2 = x2
self.y1 = y1
self.y2 = y2
self.color = color
def show_new_object(self):
quadrat2 = Display.create_rectangle(40, 50, 60, 70, fill = color)
Display.coords(quadrat2, 40, 50, 60, 70)
gui_backup.py
from tkinter import *
import curses
x1 = 10 #initialise coordinates
y1 = 10
x2 = 20
y2 = 20
root = Tk() #create window
root.wm_title("Raspberry Pi GUI") #window title
root.config(background = "#FFFFFF") #background color
#The whole left frame and widgets involved
leftFrame = Frame(root, width=200, height = 400)
leftFrame.grid(row=0, column = 0, padx = 10, pady = 3)
leftLabel1 = Label(leftFrame, text = "Platzhalter Text")
leftLabel1.grid(row = 0, column = 0, padx = 10, pady = 3)
leftLabel2 = Label(leftFrame, text = "Dies ist ein Text\nmit mehreren Zeilen")
leftLabel2.grid(row = 1, column = 0, padx = 10, pady = 3)
#the whole right frame and widgets involved
rightFrame = Frame(root, width=400, height = 400)
rightFrame.grid(row = 0, column = 1, padx = 10, pady = 3)
E1 = Entry(rightFrame, width = 50)
E1.grid(row = 0, column = 0, padx = 10, pady = 60)
#The two functions for the 2 buttons created
def callback1():
import Bauklotz_class
test = Bauklotz_class.Baustein(20, 30, 40, 50, "red")
test.show_new_object()
def callback2():
print(1+1)
buttonFrame = Frame(rightFrame)
buttonFrame.grid(row = 1, column = 0, padx = 10, pady = 60)
B1 = Button(buttonFrame, text = "Button1", bg = "#FF0000", width = 15, command = callback1)
B1.grid(row = 0, column = 0, padx = 10, pady = 60)
B2 = Button(buttonFrame, text = "Button2", bg ="#FFFF00", width = 15, command = callback2)
B2.grid(row = 0, column = 1, padx = 10, pady = 60)
Slider = Scale(rightFrame, from_ = 0, to = 100, resolution = 0.1, orient = HORIZONTAL, length = 400)
Slider.grid(row = 2, column = 0, padx = 10, pady = 3)
Display = Canvas(rightFrame, width = 300, height = 300)
Display.configure(background = 'black')
Display.grid(row = 1, column = 3, padx = 10, pady = 3)
quadrat = Display.create_rectangle(20, 30, 40, 50, fill = "blue")
Display.coords(quadrat, x1, y1, x2, y2)
#following functions are for coordination of the square
#also you can find here the exceptions so that the object
#cant break out of the display widget
def down(event):
global x1, y1, x2, y2
if x2 == 290 or y2 == 300:
pass
else:
y1 += 10
y2 += 10
Display.coords(quadrat, x1, y1, x2, y2)
leftLabel1.config(text = "x1: " + str(x1) + ", x2:" + str(x2) + ", y1:" + str(y1) + ", y2:" + str(y2), width = "40" , )
def up(event):
global x1, y1, x2, y2
if x2 == 0 or y2 == 10:
pass
else:
y1 -= 10
y2 -= 10
Display.coords(quadrat, x1, y1, x2, y2)
leftLabel1.config(text = "x1: " + str(x1) + ", x2:" + str(x2) + ", y1:" + str(y1) + ", y2:" + str(y2), width = "40" , )
def left(event):
global x1, y1, x2, y2
if x1 == 0 or y1 == 10:
pass
else:
x1 -= 10
x2 -= 10
Display.coords(quadrat, x1, y1, x2, y2)
leftLabel1.config(text = "x1: " + str(x1) + ", x2:" + str(x2) + ", y1:" + str(y1) + ", y2:" + str(y2), width = "40" , )
def right(event):
global x1, y1, x2, y2
if x1 == 290 or y1 == 300:
pass
else:
x1 += 10
x2 += 10
Display.coords(quadrat, x1, y1, x2, y2)
leftLabel1.config(text = "x1: " + str(x1) + ", x2:" + str(x2) + ", y1:" + str(y1) + ", y2:" + str(y2), width = "40" , )
root.bind('<a>', left)
root.bind('<w>', up)
root.bind('<s>', down)
root.bind('<d>', right)
root.mainloop()
Here are also some screenshots for you to understand it better:
Does someone know why my project is duplicating itself?
The problem lies within your double import, i guess. You see, you import from gui_backup.py into Bauklotz_class.py, while also importing vice versa, which leads to weird and unexpected behaviour. Also, inside the definition of show_new_object, you should use self.color instead of color as an argument for Display.create_rectangle, because self.color is a class attribute and thus the proper object to use in a class method definition. One way to fix your Problem is to add an additional attribute, let's call it canvas, to Baustein, and removing the import Display, so Bauklotz_class.py now looks like this:
class Baustein():
x1, y1, x2, y2 = 10, 10, 20, 20
color = "red"
def __init__(self, x1, y1, x2, y2, color, canvas):
self.x1 = x1
self.x2 = x2
self.y1 = y1
self.y2 = y2
self.color = color
self.canvas=canvas
def show_new_object(self):
quadrat2 = self.canvas.create_rectangle(40, 50, 60, 70, fill=self.color)
self.canvas.coords(quadrat2, 40, 50, 60, 70)
And then call it like this in gui_backup.py:
...
def callback1():
import Bauklotz_class
test = Bauklotz_class.Baustein(20, 30, 40, 50, "red", Display)
test.show_new_object()
which will fix your problem, and create a red rectangle instead of duplicating your window.
Related
I have been working on my final project, where we are supposed to create a tank game in tkinter. I have done the movement, however i´ve been struggling with the rotation of my tank. Yesterday, I manually calculated all the x and y coordinates for rotation and it works, but for some reason, when i rotate the tank for example to left, back to normal(till here it works) and then to left again the tank just completely messes up. Can´t think of reason why this is happening. Would appreciate some help.
Here is my code :
from tkinter import *
x=0
y=0
poloha="hore"
class Tank:
def __init__(self, delta) -> None:
"""""
x=input("Enter position of tank(x):")
y=input("Enter position of tank(y):")
"""""
self.t1 = plocha.create_rectangle(int(x)+50,int(y)+375,int(x)+100,int(y)+425)
self.t2 = plocha.create_rectangle(int(x)+45,int(y)+370,int(x)+50,int(y)+430)
self.t3 = plocha.create_rectangle(int(x)+100,int(y)+370,int(x)+105,int(y)+430)
self.t4 = plocha.create_rectangle(int(x)+72.5,int(y)+350,int(x)+77.5,int(y)+400)
self.delta = delta
#Movement
def left(event):
plocha.move(event.t1, -event.delta, 0)
plocha.move(event.t2, -event.delta, 0)
plocha.move(event.t3, -event.delta, 0)
plocha.move(event.t4, -event.delta, 0)
def right(event):
plocha.move(event.t1, +event.delta, 0)
plocha.move(event.t2, +event.delta, 0)
plocha.move(event.t3, +event.delta, 0)
plocha.move(event.t4, +event.delta, 0)
def up(event):
x1, y1, x2, y2 = plocha.coords(event.t4)
if y1 - 1 > 0:
plocha.move(event.t1, 0, -event.delta)
plocha.move(event.t2, 0, -event.delta)
plocha.move(event.t3, 0, -event.delta)
plocha.move(event.t4, 0, -event.delta)
else:
pass
def down(event):
x1, y1, x2, y2 = plocha.coords(event.t4)
if y2 + 1 < 500:
plocha.move(event.t1, 0, +event.delta)
plocha.move(event.t2, 0, +event.delta)
plocha.move(event.t3, 0, +event.delta)
plocha.move(event.t4, 0, +event.delta)
else:
pass
def down_turn(event):
global poloha
poloha="dole"
x1, y1, x2, y2 = plocha.coords(event.t4)
plocha.coords(event.t4, x1, y1+55, x2 , y2+55)
plocha.update()
def up_turn(event):
global poloha
if poloha=="vpravo":
x1, y1, x2, y2 = plocha.coords(event.t2)
plocha.coords(event.t2, x1, y1, x2 - 60, y2 + 55)
x1, y1, x2, y2 = plocha.coords(event.t3)
plocha.coords(event.t3, x1+55, y1-55 , x2-5 , y2)
x1, y1, x2, y2 = plocha.coords(event.t4)
plocha.coords(event.t4, x1 - 5, y1 - 50, x2 - 50, y2 - 5)
plocha.update()
if poloha=="vlavo":
x1, y1, x2, y2 = plocha.coords(event.t2)
plocha.coords(event.t2, x1 + 60, y1 - 55, x2 - 5, y2)
x1, y1, x2, y2 = plocha.coords(event.t3)
plocha.coords(event.t3, x1 + 5, y1, x2 - 60, y2 + 55)
x1, y1, x2, y2 = plocha.coords(event.t4)
plocha.coords(event.t4, x1+50, y1 - 50, x2-5, y2 +5)
plocha.update()
if poloha=="dole":
x1, y1, x2, y2 = plocha.coords(event.t4)
plocha.coords(event.t4, x1, y1 - 55, x2, y2 - 55)
plocha.update()
def right_turn(event):
global poloha
up_turn(event)
poloha="vpravo"
x1,y1,x2,y2=plocha.coords(event.t2)
plocha.coords(event.t2,x1,y1,x2+60,y2-55)
x1, y1, x2, y2 = plocha.coords(event.t3)
plocha.coords(event.t3, x1+10, y1+60, x2 -60, y2-5)
x1, y1, x2, y2 = plocha.coords(event.t4)
plocha.coords(event.t4, x1+5,y1+50,x2+50,y2-5)
plocha.update()
def left_turn(event):
global poloha
up_turn(event)
poloha="vlavo"
x1,y1,x2,y2=plocha.coords(event.t2)
plocha.coords(event.t2,x1+60,y1+55,x2-5,y2)
x1, y1, x2, y2 = plocha.coords(event.t3)
plocha.coords(event.t3, x1+5, y1,x2-60, y2-55)
x1,y1,x2,y2=plocha.coords(event.t4)
plocha.coords(event.t4, x1+5,y1+50,x2-50,y2-5)
plocha.update()
master = Tk()
master.title("WOT")
plocha = Canvas(master, width=800, height=500)
global t1,t2,t3,t4 # later delete
tank = Tank(5)
delta = 5
#Movement
plocha.bind("<w>", lambda event: up(tank))
plocha.bind("<a>", lambda event: left(tank))
plocha.bind("<s>", lambda event: down(tank))
plocha.bind("<d>", lambda event: right(tank))
plocha.bind("<Down>", lambda event: down_turn(tank))
plocha.bind("<Up>", lambda event: up_turn(tank))
plocha.bind("<Right>", lambda event: right_turn(tank))
plocha.bind("<Left>", lambda event: left_turn(tank))
plocha.focus_set()
plocha.pack()
plocha.mainloop()
I'm a newbie in programming, trying to learn python and I decided to make Tic Tac Toe for my first project. I've made functions for drawing X and O, but I have trouble drawing them in the box I'm clicking. Here's the code so far:
ttt = Tk()
ttt.title("Tic Tac Toe")
w = Canvas(ttt, width = 902, height = 902)
w.configure (bg = "white")
w.pack()
m = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
def drawx(event):
x, y = event.x, event.y
w.create_line(49, 49, 249, 249, fill = "black")
w.create_line(49, 249, 249, 49, fill = "black")
def drawo(event):
x2, y2 = event.x, event.y
x0 = x2 - 100
y0 = y2 - 100
x1 = x2 + 100
y1 = y2 + 100
return w.create_oval(x0, y0, x1, y1)
w.create_line(0, 300, 901, 300, fill = "black")
w.create_line(0, 601, 901, 601, fill = "black")
w.create_line(300, 0, 300, 901, fill = "black")
w.create_line(601, 0, 601, 901, fill = "black")
Here, the shapes will be drawn based on my cursor coordinates, which I know should be modified. Any help or suggestion would be appreciated.
You can "discretize" the x and y values by integer-dividing and then multiplying with the width of the individual cells (and adding some offset for the center).
def drawo(event):
x2, y2 = event.x, event.y
x2 = x2 // 300 * 300 + 150
y2 = y2 // 300 * 300 + 150
...
Same for drawx.
Alternatively, you could use different canvas elements (or buttons, labels or similar) for the different cells in the grid and get the clicked widget from the event.
You need to bind the mouse click event to canvas:
w.bind('<Button-1>', on_click)
Then determine which cell is clicked in on_click handler:
SIZE = 300
player = 1 # 1 for O, 2 for X
def on_click(event):
global m
global player
row = event.y // SIZE
col = event.x // SIZE
# check whether the cell is not filled yet
if m[row][col] == 0:
# calculate the center of the cell
cx = col * SIZE + SIZE // 2
cy = row * SIZE + SIZE // 2
# draw X or O based on current player
if player == 1:
draw_O(cx, cy)
else:
draw_X(cx, cy)
# set cell is filled
m[row][col] = player
# now you need to check whether current player wins
...
# if no one wins, toggle player
player = 2 if player == 1 else 1
def draw_O(x, y):
radius = SIZE // 3
w.create_oval(x-radius, y-radius, x+radius, y+radius, width=5, tag='cell') # tag is used for resetting the game
def draw_X(x, y):
radius = SIZE // 3
w.create_line(x-radius, y-radius, x+radius, y+radius, width=5, tag='cell')
w.create_line(x+radius, y-radius, x-radius, y+radius, width=5, tag='cell')
If you want to reset the game:
def reset_game():
global m
global player
# remove all 'O' and 'X'
w.delete('cell')
m = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
player = 1
For better design, put all the above logic in a class (inherited from Canvas). Then you can use instance variables instead of global variables.
To add more detail to tobias_k's answer, the below code will draw an X when the right mouse button is clicked and an O when the left mouse button is clicked.
An improvement in the code could be to use a variable to define the size of the canvas and each X/O rather than hard coding 200 or 300.
from tkinter import *
ttt = Tk()
ttt.title("Tic Tac Toe")
w = Canvas(ttt, width = 902, height = 902)
w.configure (bg = "white")
w.pack()
m = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
def drawx(event):
print("drawx")
x, y = event.x, event.y
x0 = x // 300 * 300 + 50
y0 = y // 300 * 300 + 50
x1 = x0 + 200
y1 = y0 + 200
#return w.create_oval(x0, y0, x1, y1)
w.create_line(x0,y0,x1,y1, fill = "black")
w.create_line(x0,y0+200,x1,y1-200, fill = "black")
def drawo(event):
print("drawo")
x, y = event.x, event.y
x0 = x // 300 * 300 + 50
y0 = y // 300 * 300 + 50
x1 = x0 + 200
y1 = y0 + 200
return w.create_oval(x0, y0, x1, y1)
w.create_line(0, 300, 901, 300, fill = "black")
w.create_line(0, 601, 901, 601, fill = "black")
w.create_line(300, 0, 300, 901, fill = "black")
w.create_line(601, 0, 601, 901, fill = "black")
w.bind('<Button-1>',drawo)
w.bind('<Button-3>',drawx)
ttt.mainloop()
I want to create a class and then an object which will display a red square in my display i also created.
At this moment, I can only display the blue square, which is not an object of the class "Baustein".
Here are my 2 files im using right now:
Bauklotz_class.py
from gui_backup import Display
class Baustein:
x1, y1, x2, y2 = 10,10,20,20
color = "red"
def __init__(self, x1, y1, x2, y2, color):
self.x1 = x1
self.x2 = x2
self.y1 = y1
self.y2 = y2
self.color = color
def show_new_object(self):
quadrat2 = Display.create_rectangle(40, 50, 60, 70, fill = color)
Display.coords(quadrat2, x1, y1, x2, y2)
gui_backup.py
from tkinter import *
import curses
import Bauklotz_class
x1 = 10 #initialise coordinates
y1 = 10
x2 = 20
y2 = 20
root = Tk() #create window
root.wm_title("Raspberry Pi GUI") #window title
root.config(background = "#FFFFFF") #background color
#The whole left frame and widgets involved
leftFrame = Frame(root, width=200, height = 400)
leftFrame.grid(row=0, column = 0, padx = 10, pady = 3)
leftLabel1 = Label(leftFrame, text = "Platzhalter Text")
leftLabel1.grid(row = 0, column = 0, padx = 10, pady = 3)
leftLabel2 = Label(leftFrame, text = "Dies ist ein Text\nmit mehreren Zeilen")
leftLabel2.grid(row = 1, column = 0, padx = 10, pady = 3)
#the whole right frame and widgets involved
rightFrame = Frame(root, width=400, height = 400)
rightFrame.grid(row = 0, column = 1, padx = 10, pady = 3)
E1 = Entry(rightFrame, width = 50)
E1.grid(row = 0, column = 0, padx = 10, pady = 60)
#The two functions for the 2 buttons created
def callback1():
test = Bauklotz_class.Baustein(20, 30, 40, 50, "red")
test.show_new_object()
def callback2():
print(1+1)
buttonFrame = Frame(rightFrame)
buttonFrame.grid(row = 1, column = 0, padx = 10, pady = 60)
B1 = Button(buttonFrame, text = "Button1", bg = "#FF0000", width = 15, command = callback1)
B1.grid(row = 0, column = 0, padx = 10, pady = 60)
B2 = Button(buttonFrame, text = "Button2", bg ="#FFFF00", width = 15, command = callback2)
B2.grid(row = 0, column = 1, padx = 10, pady = 60)
Slider = Scale(rightFrame, from_ = 0, to = 100, resolution = 0.1, orient = HORIZONTAL, length = 400)
Slider.grid(row = 2, column = 0, padx = 10, pady = 3)
Display = Canvas(rightFrame, width = 300, height = 300)
Display.configure(background = 'black')
Display.grid(row = 1, column = 3, padx = 10, pady = 3)
quadrat = Display.create_rectangle(20, 30, 40, 50, fill = "blue")
Display.coords(quadrat, x1, y1, x2, y2)
#following functions are for coordination of the square
#also you can find here the exceptions so that the object
#cant break out of the display widget
def down(event):
global x1, y1, x2, y2
if x2 == 290 or y2 == 300:
pass
else:
y1 += 10
y2 += 10
Display.coords(quadrat, x1, y1, x2, y2)
leftLabel1.config(text = "x1: " + str(x1) + ", x2:" + str(x2) + ", y1:" + str(y1) + ", y2:" + str(y2), width = "40" , )
def up(event):
global x1, y1, x2, y2
if x2 == 0 or y2 == 10:
pass
else:
y1 -= 10
y2 -= 10
Display.coords(quadrat, x1, y1, x2, y2)
leftLabel1.config(text = "x1: " + str(x1) + ", x2:" + str(x2) + ", y1:" + str(y1) + ", y2:" + str(y2), width = "40" , )
def left(event):
global x1, y1, x2, y2
if x1 == 0 or y1 == 10:
pass
else:
x1 -= 10
x2 -= 10
Display.coords(quadrat, x1, y1, x2, y2)
leftLabel1.config(text = "x1: " + str(x1) + ", x2:" + str(x2) + ", y1:" + str(y1) + ", y2:" + str(y2), width = "40" , )
def right(event):
global x1, y1, x2, y2
if x1 == 290 or y1 == 300:
pass
else:
x1 += 10
x2 += 10
Display.coords(quadrat, x1, y1, x2, y2)
leftLabel1.config(text = "x1: " + str(x1) + ", x2:" + str(x2) + ", y1:" + str(y1) + ", y2:" + str(y2), width = "40" , )
root.bind('<a>', left)
root.bind('<w>', up)
root.bind('<s>', down)
root.bind('<d>', right)
root.mainloop()
Now I only have the problem, that the following error is beeing generated: AttributeError: module 'Bauklotz_class' has no attribute 'Baustein'. I cant really figure out what python means by this, Im also a newbie in OOP, especialy in Python. Can someone help me with this problem?
Here is the full error message i get:
Exception in Tkinter callback Traceback (most recent call last):
File "/usr/lib/python3.5/tkinter/init.py", line 1562, in call
return self.func(*args) File "/home/pi/Documents/TKinter_Übung/gui_backup.py", line 31, in
callback1
test = Bauklotz_class.Baustein(20, 30, 40, 50, "red") AttributeError: module 'Bauklotz_class' has no attribute 'Baustein'
This line in your Callback1 function:
test = Bauklotz_class.Baustein()
needs 5 values in the brackets ('x1', 'y1', 'x2', 'y2', and 'color')
because it is calling your baustein class which ask for those parameters in the init function:
def __init__(self, x1, y1, x2, y2, color):
so... i have been stumped on this problem for some time. After researching online i have not found an answer. when i call the function: spawnLoc.getX1 from player draw line, i print it to see what it is and it prints this: and i was expecting it to print the number 30. can anyone lend a hand
import simplegui
#charictor position decliration
x1 = 30
x2 = 30
y1 = 35
y2 = 35
class Room:
def __init__(self, roomName, sizeX=0, sizeY=0):
self.roomName = roomName
self.sizeX = sizeX
self.sizeY = sizeY
class player:
def __init__(self, name, spawnLoc):
self.name = name
self.spawnLoc = spawnLoc
def draw(canvas, spawnLoc):
print spawnLoc.getX1
print spawnLoc.getX2
print spawnLoc.getY1
print spawnLoc.getY2
canvas.draw_line((spawnLoc.getX1, spawnLoc.getX2), (spawnLoc.getY1, spawnLoc.getY2), 6, 'Red')
class spawn:
def __init__(self, spawnName, spawmX1,spawmX2, spawmY1, spawmY2):
self.name = spawnName
self.x1 = spawmX1
self.x2 = spawmX2
self.y1 = spawmY1
self.y2 = spawmY2
def getX1(self):
return x1
def getX2(self):
return x2
def getY1(self):
return self.y1
def getY2(self):
return self.y2
#def Collisions(rooms, selectedPlayer):
#for Room in rooms
#if room.x == player.x
rooms = [
Room('Ticket Hall', 300, 500)
]
#spawns = [spawn('first', x1, x2, y1, y2)]
spawn('first', x1, x2, y1, y2)
player1 = [ player('one', spawn)]
#player('one', spawns)
# Handler to draw on canvas
def draw(canvas):
#room draw
canvas.draw_line((0, 0), (0, 500), 6, 'Red')
canvas.draw_line((0, 0), (300, 0), 6, 'Red')
canvas.draw_line((300, 0), (300, 500), 6, 'Red')
canvas.draw_line((0, 500), (300, 500), 6, 'Red')
#player draw
#canvas.draw_line((x1, x2), (y1, y2), 5, 'Red')
player.draw(canvas, spawn)
# Create a frame and assign callbacks to event handlers
frame = simplegui.create_frame("Home", 600, 600)
#frame.add_button("Click me", click)
frame.set_draw_handler(draw)
# Start the frame animation
frame.start()
You are forgetting the parentheses.
spawnLoc.getX1
Is a function handle.
spawnLoc.getX1()
Calls the function.
So I'm creating a script to test tkinter, which is supposed to generate random rectangles on a canvas. Here is my script:
from Tkinter import *
import random
tk = Tk()
canvas = Canvas(tk, width=400, height=400)
canvas.pack()
Option = StringVar()
Option.set("None")
menu = OptionMenu(tk, Option,"None", "Colored Outlines", "Colored Fills")
menu.pack()
option = Option.get()
button = button = Button(tk, text="Generate", command="Generate")
button.pack()
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
def random_rectangle(width, height):
x1 = random.randrange(width)
y1 = random.randrange(height)
x2 = x1 + random.randrange(width)
y2 = y1 + random.randrange(height)
canvas.create_rectangle(x1, y1, x2, y2)
def random_outline_rectangle(width, height):
x1 = random.randrange(width)
y1 = random.randrange(height)
x2 = x1 + random.randrange(width)
y2 = y1 + random.randrange(height)
color = random.choice(colors)
canvas.create_rectangle(x1, y1, x2, y2, outline = color)
def random_color_rectangle(width, height):
x1 = random.randrange(width)
y1 = random.randrange(height)
x2 = x1 + random.randrange(width)
y2 = y1 + random.randrange(height)
color = random.choice(colors)
canvas.create_rectangle(x1, y1, x2, y2, fill = color)
def Generate():
global option
if option == "None":
for x in range(0,100):
random_rectangle(400, 400)
elif option == "Colored Outlines":
for x in range(0,100):
random_outline_rectangle(400,400)
elif option == "Colored Fills":
for x in range(0,1000):
random_color_rectangle(400,400)
tk.mainloop()
So my code works perfecty without the generate button (If I remove def Generate:()) but when I run it with that, and press the button, it does nothing. Without, you must set the option by changing the code at Option.set(). I do not understand why pressing the button does nothing, however, with the original code. Any help? And how can I fix this?
Ok, I found my solution. Rawing was right, but I also needed to move the button creation to after I defined all my functions. The updated code is as follows:
from Tkinter import *
import random
tk = Tk()
canvas = Canvas(tk, width=400, height=400)
canvas.pack()
Option = StringVar()
Option.set("None")
menu = OptionMenu(tk, Option,"None", "Colored Outlines", "Colored Fills")
menu.pack()
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
def random_rectangle(width, height):
x1 = random.randrange(width)
y1 = random.randrange(height)
x2 = x1 + random.randrange(width)
y2 = y1 + random.randrange(height)
canvas.create_rectangle(x1, y1, x2, y2)
def random_outline_rectangle(width, height):
x1 = random.randrange(width)
y1 = random.randrange(height)
x2 = x1 + random.randrange(width)
y2 = y1 + random.randrange(height)
color = random.choice(colors)
canvas.create_rectangle(x1, y1, x2, y2, outline=color)
def random_color_rectangle(width, height):
x1 = random.randrange(width)
y1 = random.randrange(height)
x2 = x1 + random.randrange(width)
y2 = y1 + random.randrange(height)
color = random.choice(colors)
canvas.create_rectangle(x1, y1, x2, y2, fill=color, outline=color)
def Generate():
global option
canvas.delete("all")
if Option.get() == "None":
for x in range(0,100):
random_rectangle(400, 400)
elif Option.get() == "Colored Outlines":
for x in range(0,100):
random_outline_rectangle(400,400)
elif Option.get() == "Colored Fills":
for x in range(0,1000):
random_color_rectangle(400,400)
button = button = Button(tk, text="Generate", command=Generate)
button.pack()
tk.mainloop()