簡體   English   中英

tkinter帆布保持最小化

[英]tkinter canvas stays minimized

如何讓畫布實際上有一個尺寸?

root = Tk()
canv = Canvas(root, width=600, height=600)
canv.pack(fill = BOTH, expand = True)

root.after(1, draw)
mainloop()

只需創建一個左上角有1px畫布的窗口

編輯:我省略了繪圖,因為它沒有拋出任何東西,因此似乎沒有相關性。 但是,如果我通過pdb通過它完美運行,這里是完整的代碼:

from tkinter import *
from pdb import set_trace

class Field: #abstact
    def __init__(self, size):
        super().__init__()
        self.tiles = [[(None, 0) for i in range(size[1])] for j in     range(size[0])] #list of columns

    def get_tile(self, x,y):
        return tiles[x][y]

    def inc_tile(self, x,y,player):
        t = self.tiles[x][y]
        tiles[x][y] = (player, t[1])



class RectField(Field):
    def __init__(self, size):
        super().__init__(size)

    def select_tile(self, x, y):
        lx = len(self.tiles)
        rx = floor(x*lx)
        ly = len(self.tiles[rx])
        ry = floor(x*ly)
        return (rx, ry)

    def draw(self, canvas):
        canvas.delete(ALL)
        w = canvas.winfo_width()
        h = canvas.winfo_height()
        canvas.create_rectangle(0, 0, w, h, fill='#f0f')
        sx = w/len(self.tiles)
        for i in range(len(self.tiles)):
            sy = h/len(self.tiles[i])
            for j in range(len(self.tiles[i])):
                pl = self.tiles[i][j][0]
                cl = '#888' if not pl else ('#f20' if pl == 1 else '#02f')
                canvas.create_rectangle(i*sx, j*sy, (i+1)*sx, (j+1)*sy,     fill=cl, outline='#000')


    ##############################################################################    #####################
# MAIN
##############################################################################    #####################

root = Tk()
canv = Canvas(root, width=600, height=600)
canv.pack(fill = BOTH, expand = True)

#set_trace()
field = RectField((4,4))

def init(): 
    canv.create_rectangle(0, 0, 600, 600, fill='#f0f')
    set_trace()
    field.draw(canv)
    root.update()

root.after(1, init)
mainloop()

OS是ubuntu 16.04,python版本是預裝的python3,通過終端運行

你的畫布沒有保持最小化。 如果你給畫布一個明顯的背景顏色,你會發現它會立即填滿整個窗口,並保持這種狀態。

窗口寬度和高度都是1 ,因為在要求尺寸之前,你沒有給tkinter足夠的時間來繪制它。 winfo_widthwinfo_height返回實際高度,直到窗口在屏幕上實際可見時才能計算實際高度。

最簡單的解決方案是在調用init函數之前強制更新。 您可以通過調用update然后調用init而不是after來執行此操作。

而不是這個:

root.after(1, init)

做這個:

root.update()
init()

我能夠讓你的畫布顯示出來並且工作正常。 看起來你的init函數就是問題所在。 調用init()函數時,您無需定義等待的時間,只需直接調用它,程序將完成剩下的工作。

另外我查看了畫布的.draw()文檔,我沒有看到像.draw()這樣的東西我認為.draw()不存在這樣的函數。 我可能錯了,但如果確實存在,那么文檔並不明顯。

改用它:

def init(): 
    canv.create_rectangle(0, 0, 600, 600, fill='blue') 
    # I only changed the color to make sure it was working
    #set_trace() # not needed.
    #field.draw(canv) # does nothing?
    #root.update()  # not needed in this case.

init()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM