首页 > 解决方案 > python tkinter 尝试简化标签的东西

问题描述

所以我试图让标签变得更简单,但我找不到任何方法来做到这一点

我试图让它看起来像这样,但只有一个标签

from tkinter import *
from datetime import date
import lib

detect_date = date.today()
hari = detect_date.strftime("%A")

myWindow = Tk()
myWindow.title("Jadwal Kuliah")

def main():
    if (hari == "Monday"):
        Label(myWindow, text=lib.list_hari[0], font="none 14").pack()
        Label(myWindow, text=lib.list_mapel[0] + "|" + lib.list_waktu[0] + "|" + lib.list_kelas[1], font="none 14").pack()
        Label(myWindow, text=lib.list_dosen[0], font="none 14").pack()
        Label(myWindow, text="--------------------------------------------", font="none 14").pack()
        Label(myWindow, text=lib.list_mapel[1] + "|" + lib.list_waktu[1] + "|" + lib.list_kelas[0], font="none 14").pack()
        Label(myWindow, text=lib.list_dosen[1], font="none 14").pack()
        Label(myWindow, text="--------------------------------------------", font="none 14").pack()
        Label(myWindow, text=lib.list_mapel[2] + "|" + lib.list_waktu[2] + "|" + lib.list_kelas[9], font="none 14").pack()
        Label(myWindow, text=lib.list_dosen[2], font="none 14").pack()

Label(myWindow, text="JADWAL HARI INI", font="none 16", relief="sunken").pack()
main()

标签: python-3.xtkinter

解决方案


我喜欢做的是将按钮、标签或任何我想要的半统一的东西做成函数,用预设的设置将该对象返回给我。例子:

def my_label(frame, text):
    the_label = tkinter.Label(frame, text=text, font='none 14', fg='red')
    return the_label


first_label = my_label(myWindow, 'Some text here')
second_label = my_label(myWindow, 'Some other text here')

将返回带有这些字体和颜色设置等的标签。保持它们的标准。

目前,从您链接的图像来看,您似乎使用多个标签一次填充整个页面以适应一个条件。我用来清理它的是使用 tkinter.Text() 方法,这将允许您制作一个可以填充的大小合适的框。使用 Text() 方法,您可以...

from tkinter import *
from datetime import date
import lib

detect_date = date.today()
hari = detect_date.strftime("%A")

myWindow = Tk()
myWindow.title("Jadwal Kuliah")

def return_text_object(frame, text):
    text_object = Text(frame, font='none 14', fg='black')
    text_object.insert(text)
    return text_object

def main():
    if (hari == "Monday"):
        data_to_display = f'{text=lib.list_hari[0]}\n{lib.list_mapel[0]}|lib.list_waktu[0]}|{lib.list_kelas[1]}\n{lib.list_dosen[0]}\n--------------------------------------------\n{lib.list_mapel[1]}|{lib.list_waktu[1]}|{lib.list_kelas[0]}\n{lib.list_dosen[1]}\n--------------------------------------------\n{lib.list_mapel[2]}|{lib.list_waktu[2]}|{lib.list_kelas[9]}\n{lib.list_dosen[2]}'

        text_output = return_text_object(myWindow,data_to_display)
        text_output.pack()

Label(myWindow, text="JADWAL HARI INI", font="none 16", relief="sunken").pack()
main()

推荐阅读