Reputation: 1
This is the code for the program I'm trying to get random coordinates for to draw the random shape now the random color works but when i run the program i get this error:
(Traceback (most recent call last):
File "/home/04danielbrew/Desktop/Python/Random Coloured Square.py", line 9, in <module>
randomh=random.randint(1,1080)
AttributeError: 'builtin_function_or_method' object has no attribute 'randint)
And thanks in advance and I don't want the most advanced code as I am only doing GCSE computer science.
from tkinter import*
from random import*
####Set veriables
colors=["mintcream","orangered","gold","coral","red", "orange", "yellow", "green", "blue","violet","midnightblue"]
canvas_height=1080
canvas_width=1920
canvas_colour='black'
line_width=1
randomh=random.randint(1,1080)
randomw=random.randint(1,1920)
randomh2=random.randint(1,1080)
randomw2=random.randint(1,1920)
####Define function
def square(self):
canvas.create_line(randomh,randomw,randomh2,randomw2, width=line_width, fill=random.choice(colors))
canvas.create_line(300,100,400,100, width=line_width, fill=random.choice(colors))
canvas.create_line(400,100,400,200, width=line_width, fill=random.choice(colors))
canvas.create_line(400,200,300,200, width=line_width, fill=random.choice(colors))
###Main program
window=Tk()
window.title("Daniel Random Amazballs lines")
canvas=Canvas(bg=canvas_colour,height=canvas_height,width=canvas_width, highlightthickness=0)
canvas.pack()
###Click in window to start
window.bind("<Button-1>",square)
window.mainloop()
Upvotes: 0
Views: 5199
Reputation: 1039
As a best practice, and for Pythonic code, don't from <module> import *
.
In this case, you could use from random import randint, choice
instead.
Then your calls would look something like: randomh = randint(1,1080)
and choice(colors)
The point is that from <module> import *
is almost always the wrong way - it pollutes your top-level namespace with everything from <module>
.
Explicit is better than implicit
This isn't about advanced code, this is about learning to write code that clearly expresses your intent.
Upvotes: 3
Reputation: 3587
Since you are importing everything from random you don't need to call random.randint(), you just have to call randint() direcly.
like so:
randomh = randint(1,1080)
randomw = randint(1,1920)
randomh2 = randint(1,1080)
randomw2 = randint(1,1920)
As gomad said, it's not a good practice importing everything from a module, especially if you are using only a single method.
Also, random is supposed to be used with just import. See the difference in:
import random
random.choice([1,2,3,4])
and
from random import choice
choice([1,2,3,4])
The first one is clear what it is doing, it chooses one element in the array. While the second is unclear, does it chose the array as something? Does it present the choices to the user?
Upvotes: 1