会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 133324个问题

老师  为啥坦克和绘制文字部分显示不了   我对了好几遍代码都还找不到问题在哪

import pygame
SCREEN_WIDTH=700#屏幕高度
SCREEN_HEIGHT=500#屏幕宽度
BG_CLOLOR=pygame.Color(0,0,0)
TEXT_COLOR=pygame.Color(255,0,0)
class Mygame():#开始游戏类
    window=None
    my_tank=None
    def __init__(self):
        pass
    def starGame(self):#开始游戏方法
        pygame.display.init()#初始化窗口
        Mygame.window=pygame.display.set_mode([SCREEN_WIDTH,SCREEN_HEIGHT])#设置窗口的大小及显示
        pygame.display.set_caption('坦克大战1.03')
        #初始化坦克
        Mygame.my_tank=Tank(350,250)
        while True:
            Mygame.window.fill(BG_CLOLOR)
            pygame.display.update()#游戏窗口一直显示方法
            self.getEvent()#调用获取事件方法
            Mygame.window.blit(self.getText('敌方坦克剩余数量%d' % 6), (10, 10))
            Mygame.my_tank.displayTank()



    def endGame(self):#结束游戏方法
        print('谢谢使用  ')
        exit()
        #新增功能  左上角文字的绘制
    def getText(self,text):
        pygame.font.init()#初始化字体模块
        #print(pygame.font.get_fonts())#获取当前可用的字体
        font=pygame.font.SysFont('kaiti',18)#获取字体font对象
        #绘制文字信息
        textSurface=font.render(text,True,TEXT_COLOR)
        return textSurface


    def getEvent(self):
        eventList=pygame.event.get()#获取所以事件赋给evenList对象
        for event in eventList:#for循环事件
            if event.type==pygame.QUIT:#判断事件
                self.endGame()
            if event.type==pygame.KEYDOWN:#判断按下的上下左右
                if event.key==pygame.K_LEFT:
                    print("按下右键,坦克向左移动")
                elif event.key==pygame.K_RIGHT:
                    print("按下右键,坦克向右移动")
                elif event.key==pygame.K_UP:
                    print("按下右键,坦克向上移动")
                elif event.key == pygame.K_DOWN:
                    print("按下右键,坦克向下移动")

class Tank():#坦克类
    #添加距离左边left 距离上边top
    def __init__(self,left,top):
        #保存加载的图片
        self.images={
            'U':pygame.image.load('img/p1tankU.gif'),
            'D':pygame.image.load('img/p1tankD.gif'),
            'L':pygame.image.load('img/p1tankL.gif'),
            'R':pygame.image.load('img/p1tankR.gif'),
        }
        #方向
        self.direction = 'L'
        # 根据当前图片的方向获取图片 surface
        self.image = self.images[self.direction]
        # 根据图片获取区域
        self.rect = self.image.get_rect()
        # 设置区域的left 和top
        self.rect.left = left
        self.rect.top = top

    def move(self):#坦克移动方法
        pass
    def shot(self):#射击方法
        pass
    def displayTank(self):#展示坦克方法
        self.image=self.images[self.direction]#获取展示的对象
        Mygame.window.blit(self.image,self.rect)#调用bilt方法展示
class MyTank(Tank):#我方坦克类  继承坦克类
    def __init__(self):
        pass
class EnemtTank(Tank):
    def __init__(self):
        pass
class Bullet():
    def __init__(self):
        pass
    def move(self):
        pass
    def displayBullt(self):
        pass

class Wall():#墙壁类
    def __init__(self):
        pass
    def displayWall(self):#展示墙壁方法
        pass
class Explode():# 爆炸类
    def __init__(self):
        pass
    def displayExplode(self):#展示爆炸效果类

        pass
class Music():
    def __init__(self):
        pass
    def playMusic(self):
        pass
if __name__=="__main__":
    Mygame().starGame()


Python 全系列/第二阶段:Python 深入与提高/游戏开发-坦克大战 1336楼

import pygame, time, random

BG_COLOR = pygame.Color(0, 0, 0)
TEXT_COLOR = pygame.Color(255, 0, 0)
W_WIDTH = 700
W_HIGHT = 500


# 1、初始化
class MainTanke():
    window = None
    myTK = None
    # 创建列表储存敌方坦克
    diTanKeList = []
    # 定义敌方坦克的初始数量
    diTanKeCount = 5
    # 存储子弹列表
    BulletList = []
    # 敌方子弹列表
    diBulletList = []
    # 爆炸列表
    blastList = []
    # 墙壁列表
    wallList = []

    # 开始游戏
    def startGame(self):
        # 初始化
        pygame.display.init()
        # 设置长宽
        MainTanke.window = pygame.display.set_mode([W_WIDTH, W_HIGHT])
        # 加载坦克、初始化
        self.creatMyTanKe()
        # 初始化敌方坦克,并加入列表中
        self.creatDiTanKe()
        # 创建墙壁
        self.creatWalls()
        # 设置窗口标题
        pygame.display.set_caption('坦克1.1.1')
        # 一直显示窗口
        while True:
            # 循环频率降低
            time.sleep(0.02)
            # 设置窗口填充色
            MainTanke.window.fill(BG_COLOR)
            # 调用事件处理方法
            self.event()
            MainTanke.window.blit(self.getDiTanKeText('敌方坦克剩余数量:%d' % len(MainTanke.diTanKeList)), (10, 10))
            # 调用显示墙壁
            self.biltWalls()
            if MainTanke.myTK and MainTanke.myTK.live:
                # 显示坦克
                MainTanke.myTK.displayTanKe()
            else:
                del MainTanke.myTK
                MainTanke.myTK = None
            # 循环遍历敌方坦克列表展示敌方坦克
            self.blitDTK()
            # 判断坦克是否要移动
            if MainTanke.myTK and MainTanke.myTK.live:
                if not MainTanke.myTK.stop:
                    # 调用坦克移动方法
                    MainTanke.myTK.moveTanKe()
                    # 调用坦克碰撞墙壁的方法
                    MainTanke.myTK.hitWallTK()
            # 调用子弹方法
            self.blitBullet()
            # 调用敌方坦克子弹
            self.dBlitBullet()
            # 展示爆炸效果
            self.displayBlast()
            pygame.display.update()

    # 创建我方坦克
    def creatMyTanKe(self):
        MainTanke.myTK = TanKe(320, 420)

    # 初始化敌方坦克,加入列表
    def creatDiTanKe(self):
        top = 80
        for i in range(MainTanke.diTanKeCount):
            left = random.randint(0, 640)
            seep = random.randint(1, 6)
            diTanKe = EnemyTanKe(left, top, seep)
            MainTanke.diTanKeList.append(diTanKe)

    # 将子弹加入到窗口
    def blitBullet(self):
        for buf in MainTanke.BulletList:
            # 如果子弹活着显示,false则不显示删除
            if buf.live:
                buf.displayBullet()
                buf.moveBullet()
                # 调用子弹与坦克的碰撞
                buf.hitTanKe()
                # 子弹与墙壁的碰撞
                buf.hitWall()
            else:
                MainTanke.BulletList.remove(buf)

    # 循环遍历敌方坦克列表展示敌方坦克
    def blitDTK(self):
        for diTK in MainTanke.diTanKeList:
            if diTK.live:
                diTK.displayTanKe()
                diTK.randMove()
                diTK.hitWallTK()
                # 调用敌方坦克射击方法
                dBullet = diTK.fireBullet()
                # 将敌方子弹存入列表
                # 如果敌方子弹返回值为none则不加入列表
                if dBullet:
                    MainTanke.diBulletList.append(dBullet)
            else:
                MainTanke.diTanKeList.remove(diTK)

    # 将敌方子弹加入到窗口
    def dBlitBullet(self):
        for dbuf in MainTanke.diBulletList:
            # 如果子弹活着显示,false则不显示删除
            if dbuf.live:
                dbuf.displayBullet()
                dbuf.moveBullet()
                if MainTanke.myTK and MainTanke.myTK.live:
                    dbuf.hitMyTanKe()
                dbuf.hitWall()
            else:
                MainTanke.diBulletList.remove(dbuf)

    # 展示爆炸效果
    def displayBlast(self):
        for blas in MainTanke.blastList:
            if blas.live:
                blas.displayBlast()
            else:
                MainTanke.blastList.remove(blas)

    # 创建墙壁
    def creatWalls(self):
        for i in range(6):
            wall = Wall(130 * i, 240)
            MainTanke.wallList.append(wall)

    # 显示墙壁
    def biltWalls(self):
        for wall in MainTanke.wallList:
            if wall.live:
                wall.displayWall()
            else:
                MainTanke.wallList.remove(wall)

    # 获取敌方坦克数量
    def getDiTanKeText(self, text):
        # 初始化字体模块
        pygame.font.init()
        # 查看当前系统自带字体
        # pygame.font.get_fonts()
        # 获取字体对象
        font = pygame.font.SysFont('kaiti', 18)
        # 绘制文本信息
        diTanKeN = font.render(text, True, TEXT_COLOR)
        return diTanKeN

    # 获取事件
    def event(self):
        # 获取事件列表
        eventList = pygame.event.get()
        # 遍历事件
        for event in eventList:
            # 判断遍历的哪个事件(关闭、按键上、下、左、右)
            if event.type == pygame.QUIT:
                self.endGame()
            # 判断按下的键是什么
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE and not MainTanke.myTK:
                    # 创建我方坦克
                    self.creatMyTanKe()
                if MainTanke.myTK and MainTanke.myTK.live:
                    # 上
                    if event.key == pygame.K_UP:
                        # 切换坦克方向并且调用移动方法
                        MainTanke.myTK.direction = 'U'
                        MainTanke.myTK.stop = False
                        # MainTanke.myTK.moveTanKe()
                        print("坦克向上")
                    # 下
                    if event.key == pygame.K_DOWN:
                        # 切换坦克方向并且调用移动方法
                        MainTanke.myTK.stop = False
                        MainTanke.myTK.direction = 'D'
                        # MainTanke.myTK.moveTanKe()
                        print("坦克向下")
                    # 左
                    if event.key == pygame.K_LEFT:
                        # 切换坦克方向并且调用移动方法
                        MainTanke.myTK.direction = 'L'
                        MainTanke.myTK.stop = False
                        # MainTanke.myTK.moveTanKe()
                        print("坦克向左")
                    # 右
                    if event.key == pygame.K_RIGHT:
                        # 切换坦克方向并且调用移动方法
                        MainTanke.myTK.direction = 'R'
                        MainTanke.myTK.stop = False
                        # MainTanke.myTK.moveTanKe()
                        print("坦克向右")
                    # 空格
                    if event.key == pygame.K_SPACE:
                        print('发射子弹')
                        if len(MainTanke.BulletList) < 3:
                            # 产生一个子弹
                            m = Bullet(MainTanke.myTK)
                            # 存入列表
                            MainTanke.BulletList.append(m)
                        else:
                            print('正在填装子弹')
            # 键盘松开stop值改为True
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_UP or event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_DOWN:
                    if MainTanke.myTK and MainTanke.myTK.live:
                        MainTanke.myTK.stop = True

    # 结束游戏
    def endGame(self):
        print("成功关闭")
        exit()


# 中介商,继承精灵类
class BaseItem(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)


# 2、坦克
class TanKe(BaseItem):
    # 坦克的位置left,top
    def __init__(self, left, top):
        self.images = {
            'U': pygame.image.load('imgs/p1tankU.gif'),
            'D': pygame.image.load('imgs/p1tankD.gif'),
            'L': pygame.image.load('imgs/p1tankL.gif'),
            'R': pygame.image.load('imgs/p1tankR.gif')
        }
        # 设置坦克默认方向
        self.direction = 'U'
        # 根据方向获取图片
        self.image = self.images[self.direction]
        # 根据图片获取区域
        self.rect = self.image.get_rect()
        # 设置区域的位置
        self.rect.left = left
        self.rect.top = top
        # 设置坦克的速度
        self.speed = 5
        # 坦克的移动开关
        self.stop = True
        # 记录坦克状态
        self.live = True
        # 记录坦克移动前坐标
        self.oldLeft = self.rect.left
        self.oldTop = self.rect.top

    # 移动坦克
    def moveTanKe(self):
        # 判断坦克方向并进行移动
        if self.direction == 'U':
            if self.rect.top > 0:
                self.rect.top -= self.speed
        elif self.direction == 'D':
            if self.rect.top < 440:
                self.rect.top += self.speed
        elif self.direction == 'L':
            if self.rect.left > 0:
                self.rect.left -= self.speed
        elif self.direction == 'R':
            if self.rect.left < 640:
                self.rect.left += self.speed

    # 还原方法
    def stay(self):
        self.rect.left = self.oldLeft
        self.rect.top = self.oldTop

    # 碰撞墙壁方法
    def hitWallTK(self):
        for wall in MainTanke.wallList:
            if pygame.sprite.collide_rect(self, wall):
                self.stay()

    # 发射子弹
    def fireBullet(self):
        return Bullet(self)

    # 展示坦克
    def displayTanKe(self):
        # 获取坦克对象
        self.image = self.images[self.direction]
        # 将坦克放入画布中
        MainTanke.window.blit(self.image, self.rect)


# 2.1我方坦克
class MyTanke(TanKe):
    def __init__(self):
        pass


# 2.2敌方坦克
class EnemyTanKe(TanKe):

    def __init__(self, left, top, seep):
        super(EnemyTanKe, self).__init__(left, top)
        # 获取敌方坦克图片
        self.images = {
            'U': pygame.image.load('imgs/enemy1U.gif'),
            'D': pygame.image.load('imgs/enemy1D.gif'),
            'L': pygame.image.load('imgs/enemy1L.gif'),
            'R': pygame.image.load('imgs/enemy1R.gif')
        }
        # 设置坦克默认方向
        self.direction = self.randDirection()
        # 根据方向获取图片
        self.image = self.images[self.direction]
        # 根据图片获取区域
        self.rect = self.image.get_rect()
        # 设置区域的位置
        self.rect.left = left
        self.rect.top = top
        # 设置坦克的速度
        self.speed = random.randint(2, 6)
        # 坦克的移动开关
        self.stop = True
        # 设置坦克移动部署
        self.step = random.randint(40, 60)

    def randDirection(self):
        num = random.randint(1, 4)
        if num == 1:
            return 'U'
        if num == 2:
            return 'D'
        if num == 3:
            return 'L'
        if num == 4:
            return 'R'

    def randMove(self):
        if self.step <= 0:
            self.direction = self.randDirection()
            self.step = random.randint(40, 60)
        else:
            self.moveTanKe()
            self.step -= 1

    def fireBullet(self):
        num = random.randint(1, 50)
        if num == 50:
            return Bullet(self)


# 3、子弹
class Bullet(BaseItem):
    def __init__(self, tanke):
        # 加载图片
        self.image = pygame.image.load('imgs/enemymissile.gif')
        # 获取子弹位置
        # 子弹发射方向根据坦克方向决定
        self.direction = tanke.direction
        # 获取区域
        self.rect = self.image.get_rect()
        if self.direction == 'U':
            self.rect.top = tanke.rect.top - self.rect.height
            self.rect.left = tanke.rect.left + tanke.rect.width / 2 - self.rect.width / 2
        if self.direction == 'D':
            self.rect.top = tanke.rect.top + tanke.rect.height
            self.rect.left = tanke.rect.left + tanke.rect.width / 2 - self.rect.width / 2
        if self.direction == 'L':
            self.rect.top = tanke.rect.top + tanke.rect.width / 2 - self.rect.width / 2
            self.rect.left = tanke.rect.left - self.rect.width
        if self.direction == 'R':
            self.rect.top = tanke.rect.top + tanke.rect.width / 2 - self.rect.height / 2
            self.rect.left = tanke.rect.left + tanke.rect.width
        # 子弹的速度
        self.sppe = 7
        # 记录子弹状态
        self.live = True

    # 子弹移动
    def moveBullet(self):
        if self.direction == 'U':
            if self.rect.top > 0:
                self.rect.top -= self.sppe
            else:
                self.live = False
        if self.direction == 'D':
            if self.rect.top < W_HIGHT - self.rect.height:
                self.rect.top += self.sppe
            else:
                self.live = False
        if self.direction == 'L':
            if self.rect.left > 0:
                self.rect.left -= self.sppe
            else:
                self.live = False
        if self.direction == 'R':
            if self.rect.left < W_WIDTH - self.rect.width:
                self.rect.left += self.sppe
            else:
                self.live = False

    # 显示子弹
    def displayBullet(self):
        # 将图片加载到窗口
        MainTanke.window.blit(self.image, self.rect)

    # 子弹碰撞坦克
    def hitTanKe(self):
        for diTanke in MainTanke.diTanKeList:
            if pygame.sprite.collide_rect(diTanke, self):
                # 产生爆炸效果,将爆炸效果加入爆炸列表中
                blast = Blast(diTanke)
                MainTanke.blastList.append(blast)
                self.live = False
                diTanke.live = False

    # 子弹碰撞我方坦克
    def hitMyTanKe(self):
        if pygame.sprite.collide_rect(self, MainTanke.myTK):
            # 产生爆炸效果
            # 爆炸效果加入列表
            blast = Blast(MainTanke.myTK)
            MainTanke.blastList.append(blast)
            # 修改子弹状态
            self.live = False
            # 修稿我方坦克状态
            MainTanke.myTK.live = False

    # 子弹与墙壁碰撞
    def hitWall(self):
        for wall in MainTanke.wallList:
            if pygame.sprite.collide_rect(wall, self):
                # 修改子弹属性
                self.live = False
                # 碰撞减少生命值
                wall.hp -= 1
                # 生命值为0墙壁消失
                if wall.hp <= 0:
                    wall.live = False


# 4、爆炸效果
class Blast():
    def __init__(self, tanke):
        self.rect = tanke.rect
        self.step = 0
        self.images = [
            pygame.image.load('imgs/blast0.gif'),
            pygame.image.load('imgs/blast1.gif'),
            pygame.image.load('imgs/blast2.gif'),
            pygame.image.load('imgs/blast3.gif'),
            pygame.image.load('imgs/blast4.gif')
        ]
        self.image = self.images[self.step]
        self.live = True

    # 显示爆炸效果方法
    def displayBlast(self):
        if self.step < len(self.images):
            MainTanke.window.blit(self.image, self.rect)
            self.image = self.images[self.step]
            self.step += 1
        else:
            self.live = False
            self.step = 0


# 5、墙壁
class Wall():
    def __init__(self, left, top):
        self.image = pygame.image.load('imgs/steels.gif')
        self.rect = self.image.get_rect()
        self.rect.left = left
        self.rect.top = top
        # 判断墙壁是否展示
        self.live = True
        # 墙壁生命值
        self.hp = 3

    # 显示墙壁
    def displayWall(self):
        MainTanke.window.blit(self.image, self.rect)


# 6、音效
class Acoustics():
    def __init__(self):
        pass

    # 播放音效方法
    def startAcoustics(self):
        pass


if __name__ == '__main__':
    MainTanke().startGame()

老师,现在坦克碰到墙壁就会返回出生点,是坐标只记录了出生坐标吗

Python 全系列/第二阶段:Python 深入与提高/游戏开发-坦克大战 1337楼
Python 全系列/第二阶段:Python 深入与提高/游戏开发-坦克大战 1338楼

# 编程计算水费
import plotly as py
from plotly import figure_factory as FF
import plotly.graph_objs as pygo
import pandas as pd
import numpy as np
import csv

# 写一个txt文件
f1 = open(r"water.txt","w",encoding="utf-8")
data = "账号 1月 2月 3月 4月 5月 6月 7月 8月 9月 10月 11月 12月\n\
0000359333 772 789 806 847 880 901 950 991 1022 1043 1064 1089 1114\n\
0000359305 121 132 145 156 168 179 192 206 219 230 246 258 273\n\
0000359708 1008 1046 1102 1167 1209 1255 1311 1362 1407 1453 1512 1563 1604\n\
0000359504 541 567 590 622 651 689 701 732 758 775 796 814 847\n\
0000359209 401 412 441 466 479 490 508 522 541 572 603 637 666"
f1.write(data)

# 计算txt文件数据
f2=open("water.txt","r")
head=f2.readline()
sum=0
for line in f2.readlines():
    l=line.split()
    for i in range(len(l)/2):
        s=int(l[i*2+1])+int(l[i*2+2])*1.05
        sum+=s
print(sum)

# 将txt文件转为csv文件
data_txt = np.loadtxt('water.txt')
data_txtDF = pd.DataFrame(data_txt)
data_txtDF.to_csv('water.csv',index=False)

#绘制折线图
pyplt = py.offline.plot     #离线模式
data = pd.read_csv("water.csv",encoding="GBK")
table = FF.create_table(data)
data["水费"]=sum
xdata = data["账号"].tolist()   # 取账户这一列,做列表
ydata = data["水费"].tolist()     # 取水费这一列,做列表
trace = pygo.Scatter(x=xdata,y=ydata,name="水费")     # 水费折线
money = pygo.data(trace)
layout = pygo.Layout(title="用户一年的水费")       #图的标题
money= pygo.Figure(data=money,layout=layout)
print(money)

#关闭文件
f1.close()
f2.close()

创建水量文件“water.txt”文件,其内容第一列为账号,后面是每个月的用水量(后一个数-前一个数),共十二个月。每立方米需付1.05元。 编程计算每户一年的水费,并画出折线图。

0000359333 772  789 806 847 880 901 950 991 1022 1043 1064 1089 1114

0000359305 121  132 145 156 168 179 192 206 219 230 246 258 273

0000359708 1008 1046 1102 1167 1209 1255 1311 1362 1407 1453 1512 1563 1604

0000359504 541 567 590 622 651 689 701 732 758 775 796 814 847

0000359209 401 412 441 466 479 490 508 522 541 572 603 637 666。


老师,这道题我是先写一个txt文件,然后计算txt文件中的数据,后转成表格形式的csv文件,再用csv文件绘制折线图。因为这是昨天晚上写的,那个时候提问老师也下班了,而且掌握的不熟练,程序不长所以我就没有写一下运行一下。报的错误为:


txt文件可以正常输出,但txt文件计算数据时为0,接下来的步骤全是按照平常课程老师举的例子来写的。麻烦老师花点时间看看题目教教我,求教,谢谢!


Python 全系列/第二阶段:Python 深入与提高/文件处理 1339楼
Python 全系列/第二阶段:Python 深入与提高/异常机制 1341楼

老师,这个是我的源代码和报错的截图,请帮忙指正下哪里出了问题,谢谢。截屏2021-06-15 21.55.13.png

# 计算器软件界面的设计

from tkinter import *
from tkinter import messagebox
import random

class Application(Frame):

    def __init__(self, master=None):
        super().__init__(master)        # super()代表的是父类的定义,而不是父类对象
        self.master = master
        self.pack()
        self.createWidget()


    def createWidget(self):
        """通过grid布局实现计算器界面"""
        btnText = (("MC","M+","M-","MR"),
                   ("C","±","➗","✖️"),
                   (7,8,9,"-"),
                   (4,5,6,"+"),
                   (1,2,3,"="),
                   (0,"."))
        Entry(self).grid(row=0,column=0,cloumnspan=4,pady=10)

        for rindex, r in enumerate(btnText):
            for cindex, c in enumerate(r):
                if c == "=":
                    Button(self,text=c,width=2).grid(row=rindex+1,column=cindex,rowspan=2,sticky=NSEW)

                elif c == 0:
                    Button(self,text=c,width=2).grid(row=rindex+1,column=cindex,coloumnspan=2,sticky=NSEW)

                elif c == ".":
                    Button(self,text=c,width=2).grid(row=rindex+1,column=cindex+1,sticky=NSEW)

                else:
                    Button(self,text=c,width=2).grid(row=rindex+1,column=cindex,sticky=NSEW)


if __name__ == '__main__':
    root = Tk()
    root.geometry("300x300+200+300")
    app = Application(master=root)
    root.mainloop()


Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 1342楼
Python 全系列/第二阶段:Python 深入与提高/文件处理 1346楼

from tkinter import *
import webbrowser

class Application(Frame):

    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.creatWidget()

    def creatWidget(self):
        self.tcl = Text(root, width=60, height=20, bg='blue', fg='white')  # 宽度代表100个字符(50个字符)
        self.tcl.pack()
        self.tcl.insert(1.0, '0123456789\nabcdefghijklmn')  # 1.0代表第1行,第0列;2.5代表第2行,第5列插入字符
        self.tcl.insert(2.5, '\n君问归期未有期,\n巴山夜雨涨秋池。\n何当共剪西窗烛,\n却话巴山夜雨时。\n')

        self.tcl.btn01 = Button(self, text='重复插入文本', command=self.insertText)
        self.tcl.btn01.pack(side='left')
        Button(self, text='返回文本', command=self.returnText).pack(side='left')   # 缺点是没有变量引用,只能引用一次
        self.tcl.btn02 = Button(self, text='添加图片', command=self.addImage)
        self.tcl.btn02.pack(side='left')
        self.tcl.btn03 = Button(self, text='添加组件', command=self.addWidget)
        self.tcl.btn03.pack(side='left')
        self.tcl.btn05 = Button(self, text='通过tag精确控制文本', command=self.testTag)
        self.tcl.btn05.pack(side='left')

    def insertText(self):
        self.tcl.insert(INSERT, '惠州')   # 在光标处插入
        self.tcl.insert(END, '广州')     # 在最后插入
        self.tcl.insert(10.2, 'Ongoing')   # 在第10行,第2行插入

    def returnText(self):
        # Indexes(索引)是用来指向Text组件中文本的位置, Text的组件索引也是对应实际字符之间的位置。
        # 核心:行号以1开始,列号以0开始
        print(self.tcl.get(2.2, 2.5))  # 打印第2行 第2列到第5列的内容
        print('所有内容:\n'+self.tcl.get(1.0, END))

    def addImage(self):
        self.photo = PhotoImage(file='‪E:/Photo/Rain.gif')
        self.tcl.image_create(END, image=self.photo)

    def addWidget(self):
        btn04 = Button(self.tcl, text='深圳深圳')
        self.tcl.window_create(INSERT, window=btn04)

    def testTag(self):
        self.tcl.delete(1.0, END)
        self.tcl.insert(INSERT, 'good good study,day day up!\n广州&深圳&惠州\n百度,搜一下就知道')
        self.tcl.tag_add(' ', 1.0, 1.9)
        self.tcl.tag_config(' ', background='yellow', foreground='blue')
        self.tcl.tag_add('飞机', 3.0, 3.2)
        self.tcl.tag_config('飞机', underline=True)
        self.tcl.tag_bind('飞机', '<Button-1>', self.webshow)

    def webshow(self, event):
        webbrowser.open('http://www.baidu.com')

if __name__ == '__main__':
    root = Tk()
    root.geometry('600x500+100+100')
    root.title('广东之旅')
    app = Application(master=root)
    root.mainloop()

老师,有两个问题想咨询一下:

1、加载图片时提示无法打开,_tkinter.TclError: couldn't open "‪E:/Photo/Rain.gif": no such file or directory,我看我写的路径是对的

image.png

2、tag_add只能将对应定义的‘飞机’的属性赋给定义的3.0-3.2中‘百度’的字符,无法替换掉定义的3.0-3.2之间的字符,定义时‘飞机’这个字符是什么都不重要,与Config、Bind中对应即可,老师是这样吗

Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 1347楼
Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 1350楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637