目 录CONTENT

文章目录

PySimpleGUI实践之这个汉子怎么读?

phyger
2022-03-26 / 0 评论 / 0 点赞 / 543 阅读 / 1,297 字 / 正在检测是否收录...

背景

今天有个同学咨询我,如何才能快速入门 PythonGUI 程序开发。今天我就用一个简单且实用的例子来带领带大家快速上手。

前言

此次我们选择一做一个名为“这个汉字怎么读”的小工具。当我们看到某些不知道怎么读的汉字的时候,就可以用它来解决。

实践

环境准备

Python版本:3.7.5

安装依赖库:
pip install xpinyin
pip install PySimpleGUI

布局设计

import PySimpleGUI as sg
one_line = [sg.Text('请输入汉字'),sg.InputText(key='--IN--')]
two_line = [sg.Button('获取拼音'),sg.Button('退出')]
three_line = [sg.Text('结果:'),sg.Text(size=(20,2),key='--OUT--')]

layout = [
    one_line,
    two_line,
    three_line
]

效果图

业务代码-汉字 2 拼音

from xpinyin import Pinyin

h2p = Pinyin()

def getP(hanz,feng='-',shengd='marks'):
    return h2p.get_pinyin(hanz,splitter=feng,tone_marks=shengd)

这个汉字怎么读-整体代码

from xpinyin import Pinyin

h2p = Pinyin()

def getP(hanz,feng='-',shengd='marks'):
    return h2p.get_pinyin(hanz,splitter=feng,tone_marks=shengd)

import PySimpleGUI as sg

one_line = [sg.Text('请输入汉字'),sg.InputText(key='--IN--')]
two_line = [sg.Button('获取拼音'),sg.Button('退出')]
three_line = [sg.Text('结果:'),sg.Text(size=(20,1),key='--OUT--')]

layout = [
    one_line,
    two_line,
    three_line
]
# Create the Window
window = sg.Window('这个汉字怎么读', layout)

# 创建事件循环
while True:
    event, values = window.read()
    if event in (None, '退出'):
        # 捕捉退出事件
        break
    if event == '获取拼音':
        print(values['--IN--'])
        # 捕捉输入的汉字并翻译
        rest = getP(values['--IN--'])
        print(rest)
        # 将翻译结果更新到GUI的--OUT--对象中
        window['--OUT--'].update(rest,text_color='yellow')
        print(f'Event: {event}')
        print(str(values))

window.close()

使用效果

怎么样,这几个汉字你会读了吗?

以上就是今天的全部内容了,感谢您的阅读,我们下节再会。

0

评论区