Изменить Tkinter Label - PullRequest
       9

Изменить Tkinter Label

0 голосов
/ 05 декабря 2018

Я знаю, что это было покрыто довольно много.Однако мне не удалось решить мою проблему, несмотря на посещение каждой ссылки Stackoverflow, связанной с изменением текста метки.

Я безуспешно пытался использовать StringVar() и .configure().

То, что я пытаюсь сделать, - после выбора пользователем желаемого жанра и нажатия кнопки «Показать фильмы» будет отображена строка с фильмами, доступными в этом жанре.

Однако,Проблема, с которой я сталкиваюсь, заключается в том, что надписи продолжают накладываться друг на друга, несмотря на использование .configure () для обновления текста вместо создания еще одного сверху.

Вот небольшая демонстрация того, что мое приложениев настоящее время делает: Перекрытие метки

enter image description here

from tkinter import *
import tkinter.ttk
import tkinter.messagebox
import datetime

#
# Created by SAXAR on 04/12/2018.
#

timeNow = datetime.datetime.now()  # Creating a variable to use the date time library.

screens = ["Screen 1", "Screen 2", "Screen 3", "Screen 4", "Screen 5", "Screen 6"]

movies = {"Horror": ["The Nun", "Dracula Untold", "Feral", "Shin Godzilla", "Black Death"],
          "Action": ["Venom", "Robin Hood", "Aquaman", "Artemis Fowl", "The Predator"],
          "Drama": ["Creed", "Creed 2", "Outlaw King", "Peppermint", "Sicario: Day of the Soldado"],
          "Comedy": ["Step Brothers", "The Hangover", "Horrible Bosses", "The Other Guys", "Let's Be Cops"],
          "Sci-Fi": ["The Matrix", "Solaris", "Blade Runner", "Interstellar", "Sunshine"],
          "Romance": ["Ghost", "Sliding Doors", "50 Shades of Grey", "Titanic", "La La Land"]}



class Application(Frame):
    def __init__(self, master=None, Frame=None):
        Frame.__init__(self, master)
        super(Application, self).__init__()
        self.createWidgets()

    def updateHorror(self, event=None):
        selectedGenre = self.genreCombo.get()
        print(selectedGenre)
        return selectedGenre

    def createWidgets(self):
        # The heading for the application.
        Label(
            text="___________________________________________________________________________________________________________________________________________").place(
            x=0, y=25)
        self.headingLabel = Label(text="Cinema Bookings")
        self.headingLabel.config(font=("Roboto", 12))
        self.headingLabel.place(x=10, y=10)

        Label(text="________").place(x=10, y=65)
        Label(text="TODAY").place(x=10, y=60)
        Label(text="________").place(x=10, y=42)

        Label(text="Genre: ").place(x=70, y=60)
        self.genreCombo = tkinter.ttk.Combobox(width=15, values=list(movies.keys()), state="readonly")
        self.genreCombo.current(0)
        self.genreCombo.bind('<<ComboboxSelected>>', self.updateHorror)
        self.genreCombo.place(x=110, y=60)

        Label(
            text="___________________________________________________________________________________________________________________________________________").place(
            x=0, y=85)


        Button(text="Display Movie(s)", command=self.createLabel).place(x=585, y=265, width=100)

    def createLabel(self, event=None):

        self.movieLabel = Label(text = "")
        self.movieLabel.place(x=60, y=160)
        self.movieLabel.configure(text=" | ".join(movies.get(self.updateHorror())))


w = 700
h = 300
x = 0
y = 0

app = Application()
app.master.geometry("%dx%d+%d+%d" % (w, h, x, y))
app.master.title("Cinema Booking")
app.mainloop()

Извините за плохое кодирование.Большая часть из них - предыдущая работа из курсовой работы прошлого года.

1 Ответ

0 голосов
/ 05 декабря 2018

Причина, по которой это происходит, заключается в том, что вы создаете movielabel внутри метода createLabel().Таким образом, каждый раз, когда нажимается кнопка, создается новый movielabel , который переопределяет ранее созданную метку.

То, что вы хотите, - это одна метка, и при каждом нажатии кнопки ее текстбудет меняться соответственно.Итак, вам нужно создать метку в функции createWidgets() и просто настроить ее текст в функции createLabel.

Вот рабочий код.

from tkinter import *
import tkinter.ttk
import tkinter.messagebox
import datetime

timeNow = datetime.datetime.now()  # Creating a variable to use the date time library.

screens = ["Screen 1", "Screen 2", "Screen 3", "Screen 4", "Screen 5", "Screen 6"]

movies = {"Horror": ["The Nun", "Dracula Untold", "Feral", "Shin Godzilla", "Black Death"],
          "Action": ["Venom", "Robin Hood", "Aquaman", "Artemis Fowl", "The Predator"],
          "Drama": ["Creed", "Creed 2", "Outlaw King", "Peppermint", "Sicario: Day of the Soldado"],
          "Comedy": ["Step Brothers", "The Hangover", "Horrible Bosses", "The Other Guys", "Let's Be Cops"],
          "Sci-Fi": ["The Matrix", "Solaris", "Blade Runner", "Interstellar", "Sunshine"],
          "Romance": ["Ghost", "Sliding Doors", "50 Shades of Grey", "Titanic", "La La Land"]}

class Application(Frame):
    def __init__(self, master=None, Frame=None):
        Frame.__init__(self, master)
        super(Application, self).__init__()
        self.createWidgets()

    def updateHorror(self, event=None):
        selectedGenre = self.genreCombo.get()
        print(selectedGenre)
        return selectedGenre

    def createWidgets(self):
        # The heading for the application.
        Label(
            text="___________________________________________________________________________________________________________________________________________").place(
            x=0, y=25)
        self.headingLabel = Label(text="Cinema Bookings")
        self.headingLabel.config(font=("Roboto", 12))
        self.headingLabel.place(x=10, y=10)

        Label(text="________").place(x=10, y=65)
        Label(text="TODAY").place(x=10, y=60)
        Label(text="________").place(x=10, y=42)

        Label(text="Genre: ").place(x=70, y=60)
        self.genreCombo = tkinter.ttk.Combobox(width=15, values=list(movies.keys()), state="readonly")
        self.genreCombo.current(0)
        self.genreCombo.bind('<<ComboboxSelected>>', self.updateHorror)
        self.genreCombo.place(x=110, y=60)

        Label(
            text="___________________________________________________________________________________________________________________________________________").place(
            x=0, y=85)

        Button(text="Display Movie(s)", command=self.createLabel).place(x=585, y=265, width=100)
        self.movieLabel = Label(text = "")
        self.movieLabel.place(x=60, y=160)

    def createLabel(self, event=None):
        self.movieLabel.configure(text=" | ".join(movies.get(self.updateHorror())))

w = 700
h = 300
x = 0
y = 0

app = Application()
app.master.geometry("%dx%d+%d+%d" % (w, h, x, y))
app.master.title("Cinema Booking")
app.mainloop()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...