Iam relatively new to python and I've been trying to make a "software" with turtle and tkinter libraries, where the goal is to draw a polygon with n sides where n is the entry input in a label. Theres also a simple button which basically initiates the whole process. I've got to a point where i need to define u as the angle, whereas u=360/n;however i keep getting this error:
invalid literal for int() with base 10: ''
or unsupported operand type(s) for /: 'int' and 'StringVar
I've tried converting the output of the label to both float or int types of information, however I can't quite seem to figure it out. How should I proceed with converting the output from the entry? Any help is much appreciated and I wish anyone reading this a pleasant rest of the day. Here is the code so far:
import turtle
import random
#################
canv=tkinter.Canvas(width=400,height=400)
canv.pack()
#################
tcanv=turtle.TurtleScreen(canv)
t=turtle.RawTurtle(tcanv)
n=tkinter.StringVar()
label=tkinter.Label(text="Sides?")
label.pack()
entry=tkinter.Entry(textvariable="n")
entry.pack()
u=(360/n) if n != 0 else 0
def draw():
for i in range (n):
t.fd(50)
t.left(u)
btn=tkinter.Button (text="Draw",fg="black",command=Draw)
btn.pack()
label.mainloop()
entry.mainloop()
btn.mainloop()
You have some problems with your usage of tkinter, I suggest you try followingsome guide first.
For your code, try this:
import turtle
import tkinter as tk
def draw():
n = int(entry.get())
u = (360 / n) if n != 0 else 0
for i in range(n):
t.fd(50)
t.left(u)
if __name__ == '__main__':
root = tk.Tk()
canv = tk.Canvas(root, width=400, height=400)
canv.pack()
tcanv = turtle.TurtleScreen(canv)
t = turtle.RawTurtle(tcanv)
label = tk.Label(root, text="Sides?")
label.pack()
entry = tk.Entry(root)
entry.pack()
btn = tk.Button(text="Draw", fg="black", command=draw)
btn.pack()
root.mainloop()
(Only reordered your code and changed the string var)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.