You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
2.2 KiB
70 lines
2.2 KiB
import tkinter as tk
|
|
from tkinter import ttk
|
|
from tkinter import messagebox
|
|
|
|
# 进制转换函数
|
|
def convert_base():
|
|
try:
|
|
# 获取输入值和进制
|
|
input_num = input_entry.get().strip()
|
|
input_base = int(input_base_combobox.get())
|
|
output_base = int(output_base_combobox.get())
|
|
|
|
# 将输入数从指定进制转换为十进制
|
|
decimal_num = int(input_num, input_base)
|
|
|
|
# 将十进制数转换为目标进制
|
|
if output_base == 10:
|
|
result = str(decimal_num)
|
|
else:
|
|
result = ''
|
|
digits = "0123456789ABCDEF"
|
|
while decimal_num > 0:
|
|
result = digits[decimal_num % output_base] + result
|
|
decimal_num //= output_base
|
|
if result == '':
|
|
result = '0'
|
|
|
|
# 显示转换结果
|
|
output_entry.config(state=tk.NORMAL)
|
|
output_entry.delete(0, tk.END)
|
|
output_entry.insert(0, result)
|
|
output_entry.config(state=tk.DISABLED)
|
|
|
|
except ValueError:
|
|
messagebox.showerror("错误", "输入的数字格式不正确或超出进制范围")
|
|
|
|
# 创建主窗口
|
|
root = tk.Tk()
|
|
root.title("进制转换器")
|
|
root.geometry("400x250")
|
|
|
|
# 输入框标签和输入框
|
|
tk.Label(root, text="输入数字:").pack(pady=5)
|
|
input_entry = tk.Entry(root, width=30)
|
|
input_entry.pack(pady=5)
|
|
|
|
# 输入进制选择
|
|
tk.Label(root, text="输入数字的进制:").pack(pady=5)
|
|
input_base_combobox = ttk.Combobox(root, values=[str(i) for i in range(2, 17)], state="readonly", width=5)
|
|
input_base_combobox.current(0) # 默认选择2进制
|
|
input_base_combobox.pack(pady=5)
|
|
|
|
# 输出进制选择
|
|
tk.Label(root, text="输出数字的进制:").pack(pady=5)
|
|
output_base_combobox = ttk.Combobox(root, values=[str(i) for i in range(2, 17)], state="readonly", width=5)
|
|
output_base_combobox.current(0) # 默认选择2进制
|
|
output_base_combobox.pack(pady=5)
|
|
|
|
# 转换按钮
|
|
convert_button = tk.Button(root, text="转换", command=convert_base)
|
|
convert_button.pack(pady=10)
|
|
|
|
# 输出框标签和输出框
|
|
tk.Label(root, text="转换结果:").pack(pady=5)
|
|
output_entry = tk.Entry(root, width=30, state=tk.DISABLED)
|
|
output_entry.pack(pady=5)
|
|
|
|
# 运行主循环
|
|
root.mainloop()
|