N
N
NaitonOlgran2018-02-04 14:40:28
Python
NaitonOlgran, 2018-02-04 14:40:28

Why is the window not updated, but multiplied?

Hello everyone, tell me why in the book the example is written without mainloop, but without it nothing is displayed on the screen?
When you run this code without a loop, for some reason 6 windows fly out (one main one with a ball and 5 small empty ones), because of what?
And with a cycle, they are generated endlessly, and not the main ones with a ball, but small and empty.

import tkinter
import random
import time

class Ball:
  def __init__(self,canvas,color):
    self.canvas = canvas
    self.id = canvas.create_oval(10,10,25,25,fill=color)
    self.canvas.move(self.id, 245,100)
  def draw(self):
    pass

tk = tkinter
tk.Tk().title("game")
tk.Tk().resizable(0,0)
tk.Tk().wm_attributes("-topmost", 1)
canvas = tk.Canvas(tk.Tk(), width=500, height=400, bd=0,highlightthickness=0)
canvas.pack()
tk.Tk().update()
ball = Ball(canvas, "red")

while 1:
  tk.Tk().update_idletasks()
  tk.Tk().update()
  time.sleep(0.01)

tk.mainloop()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Avrong, 2018-02-04
@NaitonOlgran

By calling Tk() every time you create a new instance of the class, the tk=tkinter line simply assigns the library to the tk variable. To create a single window, you must call Tk() only once and then modify only one instance of the class.

from tkinter import Tk, Canvas
import random
import time

class Ball:
  def __init__(self, canvas, color):
    self.canvas = canvas
    self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
    self.canvas.move(self.id, 245, 100)
  
  def draw(self):
    pass

tk = Tk()
tk.title("game")
tk.resizable(0, 0)
tk.wm_attributes("-topmost", 1)
canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()
tk.update()
ball = Ball(canvas, "red")

while True:
  tk.update_idletasks()
  tk.update()
  time.sleep(0.01)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question