python如何用tkinter 实现歌词同步滚动,把代码写出来给我
时间: 2024-02-20 19:59:45 浏览: 106
以下是一个简单的实现歌词同步滚动的Tkinter代码,你可以根据自己的需求进行修改:
```python
import tkinter as tk
class Lyric(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.lyric_text = tk.Text(self, height=10, width=50)
self.lyric_text.pack()
self.scrollbar = tk.Scrollbar(self)
self.scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.lyric_text.config(yscrollcommand=self.scrollbar.set)
self.scrollbar.config(command=self.lyric_text.yview)
self.lyric_text.bind("<Configure>", self.on_lyric_configure)
self.lyrics = [
"Verse 1",
"I'm waking up to ash and dust",
"I wipe my brow and sweat my rust",
"I'm breathing in the chemicals",
"",
"Pre-Chorus",
"I'm breaking in, shaping up, then checking out on the prison bus",
"This is it, the apocalypse, whoa",
"",
"Chorus",
"I'm waking up, I feel it in my bones",
"Enough to make my systems blow",
"Welcome to the new age, to the new age",
"Welcome to the new age, to the new age",
"Whoa, whoa, I'm radioactive, radioactive",
"Whoa, whoa, I'm radioactive, radioactive",
"",
"Verse 2",
"I raise my flags, don my clothes",
"It's a revolution, I suppose",
"We'll paint it red to fit right in",
"",
"Pre-Chorus",
"I'm breaking in, shaping up, then checking out on the prison bus",
"This is it, the apocalypse, whoa",
"",
"Chorus",
"I'm waking up, I feel it in my bones",
"Enough to make my systems blow",
"Welcome to the new age, to the new age",
"Welcome to the new age, to the new age",
"Whoa, whoa, I'm radioactive, radioactive",
"Whoa, whoa, I'm radioactive, radioactive",
]
def on_lyric_configure(self, event):
self.lyric_text.delete('1.0', tk.END)
for i, line in enumerate(self.lyrics):
self.lyric_text.insert(tk.END, line + '\n')
if i % 4 == 0:
self.lyric_text.insert(tk.END, '\n')
if __name__ == '__main__':
root = tk.Tk()
root.geometry('300x200')
app = Lyric(root)
app.mainloop()
```
这个代码创建了一个包含歌词的 Text 组件,并且使用 Scrollbar 组件来实现滚动。在 `on_lyric_configure` 方法中,我们将歌词逐行写入 Text 组件,并且在每四行歌词之间添加一个空行。你可以根据自己的需求来修改这个方法。
阅读全文