Я знаю, что об этом много писали. Однако мне не удалось решить свою проблему, несмотря на то, что я посещал каждую ссылку Stackoverflow, которая как-то связана с изменением текста метки.
Я безуспешно пробовал использовать StringVar() и .configure().
Я пытаюсь сделать следующее: после того, как пользователь выберет желаемый жанр и нажмет «Показать фильмы», отобразится строка с фильмами, доступными для данного жанра.
Однако проблема, с которой я столкнулся, заключается в том, что метки продолжают перекрывать друг друга, несмотря на использование .configure () для обновления текста вместо создания еще одного поверх.
Вот небольшая демонстрация того, что сейчас делает мое приложение: Перекрытие этикетки
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()
Простите за плохое кодирование. По большей части это предыдущие работы по прошлогоднему курсу.






Причина этого в том, что вы создаете 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()
Ах, теперь я понял! Высоко ценим друг!