Python在tkinter中随机输出一行txt中的内容
时间: 2024-03-15 10:48:01 浏览: 132
可以使用以下代码实现:
```python
import tkinter as tk
import random
# 打开文件并读取内容
with open('file.txt', 'r') as f:
lines = f.readlines()
# 创建窗口和标签
root = tk.Tk()
label = tk.Label(root, text="")
# 随机选择一行并将其显示在标签中
line = random.choice(lines)
label.config(text=line.strip())
label.pack()
root.mainloop()
```
其中,`file.txt`是包含文本内容的文件名,可以根据实际情况进行修改。这段代码将随机选择文件中的一行,并将其显示在窗口中。
相关问题
用python的 tkinter编写俄罗斯方块
好的,以下是使用Python和Tkinter编写俄罗斯方块的基本代码:
```python
import tkinter as tk
import random
class Tetris(tk.Frame):
# 初始化游戏
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
self.parent.title("俄罗斯方块")
self.width = 300
self.height = 600
self.board = []
self.score = 0
self.init_game()
# 初始化游戏棋盘
def init_game(self):
self.canvas = tk.Canvas(self, width=self.width, height=self.height, borderwidth=0, highlightthickness=0)
self.canvas.pack(padx=10, pady=10)
self.bind_all('<Key>', self.on_key_press)
self.current_shape = None
self.next_shape = self.get_random_shape()
self.init_board()
self.score_label = tk.Label(self, text="分数: 0")
self.score_label.pack(side=tk.TOP)
self.after(1000, self.game_loop)
# 初始化游戏棋盘
def init_board(self):
for i in range(20):
row = []
for j in range(10):
row.append(0)
self.board.append(row)
# 绘制游戏棋盘
def draw_board(self):
self.canvas.delete("all")
for i in range(20):
for j in range(10):
if self.board[i][j] > 0:
self.canvas.create_rectangle(j * 30, i * 30, j * 30 + 30, i * 30 + 30, fill=self.get_color(self.board[i][j]), outline="white")
self.draw_shape(self.current_shape)
# 获取随机形状
def get_random_shape(self):
shapes = [
[[1, 1, 1], [0, 1, 0]],
[[0, 2, 2], [2, 2, 0]],
[[3, 3, 0], [0, 3, 3]],
[[4, 0, 0], [4, 4, 4]],
[[0, 0, 5, 0], [0, 5, 5, 5]],
[[6, 6], [6, 6]]
]
return random.choice(shapes)
# 绘制形状
def draw_shape(self, shape):
for i in range(len(shape)):
for j in range(len(shape[i])):
if shape[i][j] > 0:
self.canvas.create_rectangle((self.current_pos[1] + j) * 30, (self.current_pos[0] + i) * 30, (self.current_pos[1] + j) * 30 + 30, (self.current_pos[0] + i) * 30 + 30, fill=self.get_color(shape[i][j]), outline="white")
# 获取颜色
def get_color(self, val):
colors = ["black", "cyan", "yellow", "purple", "green", "red", "blue"]
return colors[val]
# 游戏循环
def game_loop(self):
if not self.current_shape:
self.current_shape = self.next_shape
self.next_shape = self.get_random_shape()
self.current_pos = [0, 4]
if self.check_collision(self.current_shape, self.current_pos):
self.game_over()
else:
self.current_pos[0] += 1
if self.check_collision(self.current_shape, self.current_pos):
self.current_pos[0] -= 1
self.freeze_shape()
self.draw_board()
self.after(500, self.game_loop)
# 检查碰撞
def check_collision(self, shape, pos):
for i in range(len(shape)):
for j in range(len(shape[i])):
if shape[i][j] > 0:
if i + pos[0] >= len(self.board) or j + pos[1] < 0 or j + pos[1] >= len(self.board[i]) or self.board[i + pos[0]][j + pos[1]] > 0:
return True
return False
# 冻结形状
def freeze_shape(self):
for i in range(len(self.current_shape)):
for j in range(len(self.current_shape[i])):
if self.current_shape[i][j] > 0:
self.board[self.current_pos[0] + i][self.current_pos[1] + j] = self.current_shape[i][j]
self.current_shape = None
self.check_lines()
# 检查行
def check_lines(self):
lines = 0
for i in range(len(self.board)):
if 0 not in self.board[i]:
lines += 1
self.board.pop(i)
self.board.insert(0, [0 for _ in range(10)])
self.score += lines * 10
self.score_label.config(text="分数: {}".format(self.score))
# 处理键盘事件
def on_key_press(self, event):
if event.keysym == 'Left':
self.current_pos[1] -= 1
if self.check_collision(self.current_shape, self.current_pos):
self.current_pos[1] += 1
elif event.keysym == 'Right':
self.current_pos[1] += 1
if self.check_collision(self.current_shape, self.current_pos):
self.current_pos[1] -= 1
elif event.keysym == 'Up':
self.rotate_shape()
elif event.keysym == 'Down':
self.current_pos[0] += 1
if self.check_collision(self.current_shape, self.current_pos):
self.current_pos[0] -= 1
self.freeze_shape()
# 旋转形状
def rotate_shape(self):
new_shape = []
for i in range(len(self.current_shape[0])):
row = []
for j in range(len(self.current_shape) - 1, -1, -1):
row.append(self.current_shape[j][i])
new_shape.append(row)
if not self.check_collision(new_shape, self.current_pos):
self.current_shape = new_shape
# 游戏结束
def game_over(self):
self.canvas.delete("all")
self.canvas.create_text(self.width / 2, self.height / 2, text="游戏结束", font=("Helvetica", 32))
if __name__ == '__main__':
root = tk.Tk()
game = Tetris(root)
game.pack()
root.mainloop()
```
这段代码使用了Tkinter创建了一个窗口,并在其中绘制了俄罗斯方块的游戏棋盘。在游戏中,使用方向键控制方块的移动和旋转,当方块堆积到底部时会被固定,如果一行被填满则会消除并得分。当方块堆积到顶部时游戏结束。
希望对你有所帮助!
使用python程序,实现从txt文本中随机取一行文本,在windows电脑屏幕上以弹幕的形式从右向左滑动,并且能够实现,每隔30秒自动更新一次弹幕
在Python中实现这个功能需要用到`tkinter`库来创建窗口和动画效果,以及`random`库来随机选取文本行。以下是一个简单的示例代码,用于在Windows上创建一个带有弹幕效果的窗口:
```python
import tkinter as tk
from tkinter import messagebox
import random
import time
# 假设text_file.txt是存放弹幕内容的文件
def load_text_from_file(file_name):
with open(file_name, 'r', encoding='utf-8') as f:
lines = f.readlines()
return [line.strip() for line in lines] # 删除末尾换行符并存储为列表
# 读取弹幕文本
text_lines = load_text_from_file('text_file.txt')
class TextScroller(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.canvas = tk.Canvas(self, width=500, height=500, bg="black", bd=0, highlightthickness=0)
self.text_label = tk.Label(self.canvas, text=text_lines, font=("Arial", 20), fill=tk.BOTH, wraplength=480,
justify=tk.LEFT, anchor=tk.NW)
self.update_text()
def update_text(self):
self.text_label.config(text=random.choice(text_lines))
x = 0
y = self.canvas.winfo_height()
self.canvas.create_rectangle(x, y, x + 480, y - 40, fill="white")
self.text_label.place(x=x, y=y)
self.canvas.after(10, self.update_text)
root = tk.Tk()
app = TextScroller(root)
app.mainloop()
# 更新间隔30秒
while True:
root.update_idletasks()
time.sleep(30)
app.update_text()
```
注意:
1. 需要在相同的目录下有一个名为'text_file.txt'的文本文件,里面包含你想要显示的弹幕文字。
2. 这个脚本会在Tkinter的主线程中运行,如果希望在每隔30秒后自动刷新弹幕,可能会导致界面卡顿。为了更流畅的用户体验,你可以考虑使用定时任务或者其他异步处理方式(如协程或线程)。
阅读全文