簡體   English   中英

tkinter 網格重疊

[英]tkinter grid overlapping

我正在構建一個日歷,允許用戶通過按下上個月和下個月創建的按鈕來循環瀏覽月份和年份。 本質上,我希望主要的 window 做的是在單擊 PREV 或 NEXT 月份並使用正確的日期更新新月份,它確實如此,唯一的問題是顯示月份特定日期的日期按鈕在循環時重疊。 以下是我遇到問題的部分:

def prevMonth(self):
        try:
            self.grid_forget()
            #SHOULD REFRESH THE WINDOW SO BUTTONS DONT OVERLAP
            print "forgeting" 

        except:
            print "passed the forgetting"
            pass
        lastMonth = self.month - 1 
        self.month = lastMonth
        self.curr_month()

    def nextMonth(self):
        try:
            self.grid_forget()
            #SHOULD REFRESH THE WINDOW SO BUTTONS DONT OVERLAP
            print "forgeting"

        except:
            print "passed the forgetting"
            pass
        nextMonth = self.month + 1
        self.month = nextMonth
        self.curr_month()

當程序在月份之間迭代時,網格不會刷新它只是與日期和月份重疊。 我已經嘗試了我在研究中發現的一切。 “self.destroy()”僅創建一個空白 window。“self.grid.destroy()”返回錯誤,function 沒有屬性 destroy。 我已經嘗試讓網格的子項成為自我中的所有全局變量,但我無法正確地迭代幾個月,因此設置是永久性的,但我覺得我缺少一些簡單的東西,比如刷新網格並重新打印基於更新月份。

你能指出我正確的方向或糾正我遺漏的錯誤嗎?

下面是整個程序

from Tkinter import *
from calendar import *
import datetime

class Application(Frame):

def __init__(self, master=None):
    Frame.__init__(self, master)
    self.grid()
    DateNow = datetime.datetime.now()
    self.year = DateNow.year#declaring global variable year
    self.month = DateNow.month#declaring global variable month
    self.curr_month()



def curr_month(self):
    try:#iterating the month and year backward if index is out of range
        if self.month == 0:
            self.month = 12
            trueYear = int(self.year)
            self.year = trueYear - 1
    except:
        pass
    try:#iterating month and year forward if index is out of range
        if self.month == 13:
            self.month = 1
            trueYear = int(self.year)
            self.year = trueYear + 1
    except:
        pass


    days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
#create labels


    self.label = Label(self, text=months[self.month - 1])#displaying month
    self.label.grid(row=0, column = 1)
    self.label = Label(self, text=self.year)#displaying year
    self.label.grid(row=0, column = 6)


    try:#displaying previous month
        prevMonthBut = Button(self, text=months[self.month-2], command=self.prevMonth)
        prevMonthBut.grid(row=0,column=0)
    except:#USED ONLY IF PREVIOUS MONTH IS IN PREVIOUS YEAR
        prevMonthBut = Button(self, text=months[11], command=self.prevMonth)
        prevMonthBut.grid(row=0,column=0)
    try:#displaying next month 
        nextMonthBut = Button(self, text=months[self.month], command=self.nextMonth)
        nextMonthBut.grid(row=0,column=2)
    except:#USED ONLY IF NEXT MONTH IS IN NEXT YEAR
        nextMonthBut = Button(self, text=months[0], command=self.nextMonth)
        nextMonthBut.grid(row=0,column=2)
    for i in range(7):
        self.label = Label(self, text=days[i])
        self.label.grid(row = 1, column = i)

    weekday, numDays = monthrange(self.year, self.month)
    week = 2
    for i in range(1, numDays + 1):
        self.button = Button(self, text = str(i))
        self.button.grid(row = week, column = weekday)

        weekday += 1

        if weekday > 6:
            week += 1
            weekday = 0


def prevMonth(self):
    try:
        self.grid_forget()
        #SHOULD REFRESH THE WINDOW SO BUTTONS DONT OVERLAP
        print "forgeting" 

    except:
        print "passed the forgetting"
        pass
    lastMonth = self.month - 1 
    self.month = lastMonth
    self.curr_month()

def nextMonth(self):
    try:
        self.grid_forget()
        #SHOULD REFRESH THE WINDOW SO BUTTONS DONT OVERLAP
        print "forgeting"

    except:
        print "passed the forgetting"
        pass
    nextMonth = self.month + 1
    self.month = nextMonth
    self.curr_month()

mainWindow = Tk()
obj = Application()
mainWindow.mainloop()here

這是建議答案的修改版本,其中還包括允許用戶循環使用月份並增加年份的最初預期意圖。

from calendar import *
import datetime
try:
    from tkinter import *   # Python 3.x
except:
    from Tkinter import *   # Python 2.x


class Application(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.grid(row=0, column=0, sticky='news')
        DateNow = datetime.datetime.now()
        self.month = int(DateNow.month)
        self.year = int(DateNow.year)
        self.createDaysOfWeekLabels()

        # Create frames and button controls for previous, current and next month.
        self.frameList = []    # List that contains the frame objects.
        self.buttonList = []   # List that contains the button objects.
        self.split()

    def split(self):
        month_name = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
        leftArrow = Button(self, text="<", command=self.prevMonth)
        leftArrow.grid(row = 0, column = 0)
        rightArrow = Button(self, text=">", command=self.nextMonth)
        rightArrow.grid(row = 0, column = 1)
        for i in range(3):
            try:
                print i, "this is i"
                print self.month
                mFrame = Frame(self)
                self.createMonth(mFrame)
                self.frameList.append(mFrame)
                mButton = Button(self, text=month_name[self.month-1])
                mButton['command'] = lambda f=mFrame, b=mButton: self.showMonth(f, b)
                mButton.grid(row=1, column=i)
                # Grid each frame
                mFrame.grid(row=3, column=0, columnspan=7, sticky='news')
                if (i == 1):
                    mButton['relief'] = 'flat'
                else:
                    mButton.grid_remove()
                    # Remove all but the ith frame. More efficient to remove than forget and configuration is remembered.
                    mFrame.grid_remove()          
                self.buttonList.append(mButton)

            except:
                pass
        # Create year widget at top right of top frame
        label = Label(self, text=self.year)#displaying year
        label.grid(row=0, column=6)
        print "-------------------"

    def prevMonth(self):

        self.month -= 1
        print self.month, "this is month in PREV"
        if self.month <= 0:
            self.month = 12
            print self.month, "month inside forinif in PREVMONTH"
            self.year -= 1
        elif self.month >= 13:
            self.month = 0
            print self.month, "month inside forinelif in PREVMONTH"
            self.year += 1
        self.split()

    def nextMonth(self):

        self.month += 1
        print self.month, "this is month in NEXT"
        for frame in self.frameList:
            frame.grid_remove()

        if self.month <= -1:
            self.month = 11
            print self.month, "month inside forinif in NEXTMONTH"
            self.year -= 1
        elif self.month >= 13:
            self.month = 1
            print self.month, "month inside forinelif in NEXTMONTH"
            self.year += 1
        self.split()


    def createDaysOfWeekLabels(self):
        days = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
        for i in range(7):
            label = Label(self, text=days[i], width = 3)
            label.grid(row = 2, column = i)

    def showMonth(self, mFrame, mButton):
        # Display all buttons normally
        for button in self.buttonList:
            button['relief'] = 'raised'

        # Set this month's button relief to flat
        mButton['relief'] = 'flat'

        # Hide all frames
        for mframe in self.frameList:
            mframe.grid_remove()

        mFrame.grid()

    def createMonth(self, mFrame):

        weekday, numDays = monthrange(self.year, self.month)
        week = 0
        for i in range(1, numDays + 1):
            button = Button(mFrame, text = str(i), width=3)
            button.grid(row = week, column = weekday)

            weekday += 1

            if weekday > 6:
                week += 1
                weekday = 0

mainWindow = Tk()
obj = Application(mainWindow)
mainWindow.mainloop()

Tkinter非常有效。 對於您擁有的小部件數量,最初創建它們不會對性能產生太大影響。 這是一個與您嘗試執行的操作類似的示例。

from calendar import *
import datetime
try:
    from tkinter import *   # Python 3.x
except:
    from Tkinter import *   # Python 2.x


class Application(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.grid(row=0, column=0, sticky='news')

        DateNow = datetime.datetime.now()
        month = int(DateNow.month)
        year = int(DateNow.year)
        self.createDaysOfWeekLabels()
        month_name = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
        # Create frames and button controls for previous, current and next month.
        self.frameList = []    # List that contains the frame objects.
        self.buttonList = []   # List that contains the button objects.
        amonth = month - 1
        for i in range(3):
            if amonth < 0:
                amonth = 11
                year -= 1
            elif amonth == 12:
                amonth = 0
                year += 1

            mFrame = Frame(self)
            self.createMonth(mFrame, amonth, year)
            self.frameList.append(mFrame)
            mButton = Button(self, text=month_name[amonth-1])
            mButton['command'] = lambda f=mFrame, b=mButton: self.showMonth(f, b)
            mButton.grid(row=0, column=i)
            # Grid each frame
            mFrame.grid(row=2, column=0, columnspan=7, sticky='news')
            if (i == 1):
                mButton['relief'] = 'flat'
            else:
                # Remove all but the ith frame. More efficient to remove than forget and configuration is remembered.
                mFrame.grid_remove()
            self.buttonList.append(mButton)
            amonth += 1

        # Create year widget at top left of top frame
        label = Label(self, text=year)#displaying year
        label.grid(row=0, column=6)


    def createDaysOfWeekLabels(self):
        days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        for i in range(7):
            label = Label(self, text=days[i])
            label.grid(row = 1, column = i)

    def showMonth(self, mFrame, mButton):
        # Display all buttons normally
        for button in self.buttonList:
            button['relief'] = 'raised'

        # Set this month's button relief to flat
        mButton['relief'] = 'flat'

        # Hide all frames
        for frame in self.frameList:
            frame.grid_remove()

        mFrame.grid()

    def createMonth(self, mFrame, month, year):
        weekday, numDays = monthrange(year, month)
        week = 0
        for i in range(1, numDays + 1):
            button = Button(mFrame, text = str(i), width=3)
            button.grid(row = week, column = weekday)

            weekday += 1

            if weekday > 6:
                week += 1
                weekday = 0

mainWindow = Tk()
obj = Application(mainWindow)
mainWindow.mainloop()

使用類似 [yourWidget].grid(row=0, column=0, columnspan=4)

暫無
暫無

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

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