Pyhton 中的数字转换

问题描述 投票:0回答:1

我正在制作一个计算器,我想添加数字转换的功能,但它似乎不起作用。这就是我的目标:当我单击 BIN 按钮(或任何数字转换按钮)时,它会将其键入,然后我键入二进制数字,然后单击任何其他数字转换。按钮,例如 DEC,它会输入它,当我按下等号按钮时,它应该给我十进制的二进制数,但事实并非如此。我将不胜感激任何帮助。谢谢。

这是我的代码:

from tkinter import *
from tkinter import filedialog
from tkinter import simpledialog, messagebox
import tkinter.messagebox
import math
root = Tk()
root.geometry("650x400+300+300")
root.title("Scientific Calculator")
switch = None

# Button on press
def dat_clicked():
    file_path = filedialog.askopenfilename(filetypes=[('Text Files', '*.txt')])
    
    if file_path:
        with open(file_path, 'r') as file:
            content = file.read().replace('\n', '')
            disp.delete(0, END)  # Clear previous content
   
            pos = len(disp.get())
            disp.insert(pos, content)

def btn1_clicked():
    if disp.get() == '0':
        disp.delete(0, END)
    pos = len(disp.get())
    disp.insert(pos, '1')
def btn2_clicked():
    if disp.get() == '0':
        disp.delete(0, END)
    pos = len(disp.get())
    disp.insert(pos, '2')
def btn3_clicked():
    if disp.get() == '0':
        disp.delete(0, END)
    pos = len(disp.get())
    disp.insert(pos, '3')
def btn4_clicked():
    if disp.get() == '0':
        disp.delete(0, END)
    pos = len(disp.get())
    disp.insert(pos, '4')
def btn5_clicked():
    if disp.get() == '0':
        disp.delete(0, END)
    pos = len(disp.get())
    disp.insert(pos, '5')
def btn6_clicked():
    if disp.get() == '0':
        disp.delete(0, END)
    pos = len(disp.get())
    disp.insert(pos, '6')
def btn7_clicked():
    if disp.get() == '0':
        disp.delete(0, END)
    pos = len(disp.get())
    disp.insert(pos, '7')
def btn8_clicked():
    if disp.get() == '0':
        disp.delete(0, END)
    pos = len(disp.get())
    disp.insert(pos, '8')
def btn9_clicked():
    if disp.get() == '0':
        disp.delete(0, END)
    pos = len(disp.get())
    disp.insert(pos, '9')
def btn0_clicked():
    if disp.get() == '0':
        disp.delete(0, END)
    pos = len(disp.get())
    disp.insert(pos, '0')

def key_event(*args):
    if disp.get() == '0':
        disp.delete(0, END)

def btnp_clicked():
    pos = len(disp.get())
    disp.insert(pos, '+')
def btnm_clicked():
    pos = len(disp.get())
    disp.insert(pos, '-')
def btnml_clicked():
    pos = len(disp.get())
    disp.insert(pos, '*')
def btnd_clicked():
    pos = len(disp.get())
    disp.insert(pos, '/')

def btnc_clicked(*args):
    disp.delete(0, END)
    disp.insert(0, '0')

def btn_clicked(value):
    if disp.get() == '0':
        disp.delete(0, END)
    pos = len(disp.get())
    disp.insert(pos, value)
def conv_btn_clicked(value):
    global conversion_type
    conversion_type = value
    disp.insert(END, " " + conversion_type + " ")

def calculate_result():
    global conversion_type
    try:
        expression = disp.get()
        if conversion_type:
            conversion_result = convert_to_target_base(expression, conversion_type)
            disp.delete(0, END)
            disp.insert(0, str(conversion_result))
            conversion_type = None  # Reset conversion_type after use
        else:
            result = eval(expression)
            disp.delete(0, END)
            disp.insert(0, str(result))
    except Exception as e:
        tkinter.messagebox.showerror("Value Error", f"Check your input: {str(e)}")

def convert_to_target_base(value, target_base):
    last_space_index = value.rfind(' ')
    if last_space_index == -1:
        raise ValueError("Invalid input format")

    num = value[:last_space_index]
    source_base = value[last_space_index+1:]

    allowed_bases = {"BIN": 2, "OCT": 8, "HEX": 16, "DEC": 10}

    if source_base not in allowed_bases or target_base not in allowed_bases:
        raise ValueError("Invalid input format")

    decimal_value = int(num, allowed_bases[source_base])

    if target_base == "BIN":
        result = bin()[2:]
    elif target_base == "OCT":
        result = oct(decimal_value)[2:]
    elif target_base == "HEX":
        result = hex(decimal_value)[2:].upper()
    else:
        result = str(decimal_value)

    return f"{result} {target_base}"


def dec_btn_clicked():
    pos = len(disp.get())
    disp.insert(pos, ' DEC ')
def bin_btn_clicked():
    pos = len(disp.get())
    disp.insert(pos, ' BIN ')

def oct_btn_clicked():
    pos = len(disp.get())
    disp.insert(pos, ' OCT ')

def hex_btn_clicked():
    pos = len(disp.get())
    disp.insert(pos, ' HEX ')
def tan_clicked():
    try:
        ans = float(disp.get())
        if switch is True:
            ans = math.tan(math.radians(ans))
        else:
            ans = math.tan(ans)
            disp.delete(0, END)
            disp.insert(0, str(ans))
    except Exception:
        tkinter.messagebox.showerror("Value Error", "Check your values and operators")
def arcsin_clicked():
    try:
        ans = float(disp.get())
        if switch is True:
            ans = math.degrees(math.asin(ans))
        else:
            ans = math.asin(ans)
            disp.delete(0, END)
            disp.insert(0, str(ans))
    except Exception:
        tkinter.messagebox.showerror("Value Error", "Check your values and operators")
def arccos_clicked():
    try:
        ans = float(disp.get())
        if switch is True:
            ans = math.degrees(math.acos(ans))
        else:
            ans = math.acos(ans)
            disp.delete(0, END)
            disp.insert(0, str(ans))
    except Exception:
            tkinter.messagebox.showerror("Value Error", "Check your values and operators")
def arctan_clicked():
    try:
        ans = float(disp.get())
        if switch is True:
            ans = math.degrees(math.atan(ans))
        else:
            ans = math.atan(ans)
            disp.delete(0, END)
            disp.insert(0, str(ans))
    except Exception:
        tkinter.messagebox.showerror("Value Error", "Check your values and operators")
def pow_clicked():
    pos = len(disp.get())
    disp.insert(pos, '**')
def round_clicked():
    try:
        ans = float(disp.get())
        ans = round(ans)
        disp.delete(0, END)
        disp.insert(0, str(ans))
    except Exception:
        tkinter.messagebox.showerror("Value Error", "Check your values and operators")
def logarithm_clicked():
    try:
        ans = float(disp.get())
        ans = math.log10(ans)
        disp.delete(0, END)
        disp.insert(0, str(ans))
    except Exception:
        tkinter.messagebox.showerror("Value Error", "Check your values and operators")
def sqr_clicked():
    try:
        ans = float(disp.get())
        ans = math.sqrt(ans)
        disp.delete(0, END)
        disp.insert(0, str(ans))
    except Exception:
        tkinter.messagebox.showerror("Value Error", "Check your values and operators")
def dot_clicked():
    pos = len(disp.get())
    disp.insert(pos, '.')
def e_clicked():
    if disp.get() == '0':
        disp.delete(0, END)
        pos = len(disp.get())
        disp.insert(pos, str(math.e))
def bl_clicked():
    pos = len(disp.get())
    disp.insert(pos, '(')
def br_clicked():
    pos = len(disp.get())
    disp.insert(pos, ')')
def del_clicked():
    pos = len(disp.get())
    display = str(disp.get())
    if display == '':
        disp.insert(0, '0')
    elif display == ' ':
        disp.insert(0, '0')
    elif display == '0':
        pass
    else:
        disp.delete(0, END)
        disp.insert(0, display[0:pos-1])
def conv_clicked():
    global switch
    if switch is None:
        switch = True
        conv_btn['text'] = "Deg"
    else:
        switch = None
        conv_btn['text'] = "Rad"
def ln_clicked():
    try:
        ans = float(disp.get())
        ans = math.log(ans)
        disp.delete(0, END)
        disp.insert(0, str(ans))
    except Exception:
        tkinter.messagebox.showerror("Value Error", "Check your values and operators")
def mod_clicked():
    pos = len(disp.get())
def btneq_clicked():
    global conversion_type  # Declare conversion_type as a global variable
    try:
        expression = disp.get()
        if conversion_type:
            conversion_result = convert_to_target_base(expression, conversion_type)
            disp.delete(0, END)
            disp.insert(0, str(conversion_result))
            conversion_type = None  # Reset conversion_type after use
        else:
            result = eval(expression)
            disp.delete(0, END)
            disp.insert(0, str(result))
    except Exception as e:
        tkinter.messagebox.showerror("Value Error", f"Check your input: {str(e)}")

# Label
data = StringVar()
disp = Entry(root, font="Verdana 20", fg="black", bg="mistyrose", bd=4, justify=RIGHT, insertbackground="#abbab1", cursor="arrow")
#disp.bind("<Return>", btneq_clicked)
#disp.bind("<Escape>", btnc_clicked)
#disp.bind("<Key-1>", key_event)
#disp.bind("<Key-2>", key_event)
#disp.bind("<Key-3>", key_event)
#disp.bind("<Key-4>", key_event)
#disp.bind("<Key-5>", key_event)
#disp.bind("<Key-6>", key_event)
#disp.bind("<Key-7>", key_event)
#disp.bind("<Key-8>", key_event)
#disp.bind("<Key-9>", key_event)
#disp.bind("<Key-0>", key_event)
#disp.bind("<Key-.>", key_event)
#disp.insert(0, '0')
#disp.focus_set()
disp.pack(expand=TRUE, fill=BOTH)
# Row 1 Buttons
btnrow1 = Frame(root, bg="#000000")
btnrow1.pack(expand=TRUE, fill=BOTH)
dec_btn = Button(btnrow1, text="DEC", font="Segoe 10 bold", relief=GROOVE, bd=0, command=dec_btn_clicked, fg="white", bg="#333333")
dec_btn.pack(side=LEFT, expand=TRUE, fill=BOTH)

bin_btn = Button(btnrow1, text="BIN", font="Segoe 10 bold", relief=GROOVE, bd=0, command=bin_btn_clicked, fg="white", bg="#333333")
bin_btn.pack(side=LEFT, expand=TRUE, fill=BOTH)

oct_btn = Button(btnrow1, text="OCT", font="Segoe 10 bold", relief=GROOVE, bd=0, command=oct_btn_clicked, fg="white", bg="#333333")
oct_btn.pack(side=LEFT, expand=TRUE, fill=BOTH)

hex_btn = Button(btnrow1, text="HEX", font="Segoe 10 bold", relief=GROOVE, bd=0, command=hex_btn_clicked, fg="white", bg="#333333")
hex_btn.pack(side=LEFT, expand=TRUE, fill=BOTH)
mod_btn = Button(btnrow1, text="%", font="Segoe 21", relief=GROOVE, bd=0, command=mod_clicked, fg="white", bg="#333333")
mod_btn.pack(side=LEFT, expand=TRUE, fill=BOTH)
btn1 = Button(btnrow1, text="1", font="Segoe 23", relief=GROOVE, bd=0, command=btn1_clicked, fg="white", bg="#333333")
btn1.pack(side=LEFT, expand=TRUE, fill=BOTH)
btn2 = Button(btnrow1, text="2", font="Segoe 23", relief=GROOVE, bd=0, command=btn2_clicked, fg="white", bg="#333333")
btn2.pack(side=LEFT, expand=TRUE, fill=BOTH)
btn3 = Button(btnrow1, text="3", font="Segoe 23", relief=GROOVE, bd=0, command=btn3_clicked, fg="white", bg="#333333")
btn3.pack(side=LEFT, expand=TRUE, fill=BOTH)
btnp = Button(btnrow1, text="+", font="Segoe 23", relief=GROOVE, bd=0, command=btnp_clicked, fg="white", bg="#333333")
btnp.pack(side=LEFT, expand=TRUE, fill=BOTH)
# Row 2 Buttons
btnrow2 = Frame(root)
btnrow2.pack(expand=TRUE, fill=BOTH)
e_btn = Button(btnrow2, text="e", font="Segoe 18", relief=GROOVE, bd=0, command=e_clicked, fg="white", bg="#333333")
e_btn.pack(side=LEFT, expand=TRUE, fill=BOTH)
logarithm_btn = Button(btnrow2, text="log", font="Segoe 17", relief=GROOVE, bd=0, command=logarithm_clicked, fg="white", bg="#333333")
logarithm_btn.pack(side=LEFT, expand=TRUE, fill=BOTH)
tanh_btn = Button(btnrow2, text="tan-1", font="Segoe 11 bold", relief=GROOVE, bd=0, command=arctan_clicked, fg="white", bg="#333333")
tanh_btn.pack(side=LEFT, expand=TRUE, fill=BOTH)
bl_btn = Button(btnrow2, text=" ( ", font="Segoe 21", relief=GROOVE, bd=0, command=bl_clicked, fg="white", bg="#333333")
bl_btn.pack(side=LEFT, expand=TRUE, fill=BOTH)
br_btn = Button(btnrow2, text=" ) ", font="Segoe 21", relief=GROOVE, bd=0, command=br_clicked, fg="white", bg="#333333")
br_btn.pack(side=LEFT, expand=TRUE, fill=BOTH)
btn4 = Button(btnrow2, text="4", font="Segoe 23", relief=GROOVE, bd=0, command=btn4_clicked, fg="white", bg="#333333")
btn4.pack(side=LEFT, expand=TRUE, fill=BOTH)
btn5 = Button(btnrow2, text="5", font="Segoe 23", relief=GROOVE, bd=0, command=btn5_clicked, fg="white", bg="#333333")
btn5.pack(side=LEFT, expand=TRUE, fill=BOTH)
btn6 = Button(btnrow2, text="6", font="Segoe 23", relief=GROOVE, bd=0, command=btn6_clicked, fg="white", bg="#333333")
btn6.pack(side=LEFT, expand=TRUE, fill=BOTH)
btnm = Button(btnrow2, text="-", font="Segoe 23", relief=GROOVE, bd=0, command=btnm_clicked, fg="white", bg="#333333")
btnm.pack(side=LEFT, expand=TRUE, fill=BOTH)
# Row 3 Buttons
btnrow3 = Frame(root)
btnrow3.pack(expand=TRUE, fill=BOTH)
conv_btn = Button(btnrow3, text="Rad", font="Segoe 12 bold", relief=GROOVE, bd=0, command=conv_clicked, fg="white", bg="#FF69B4")
conv_btn.pack(side=LEFT, expand=TRUE, fill=BOTH)
round_btn = Button(btnrow3, text="round", font="Segoe 10 bold", relief=GROOVE, bd=0, command=round_clicked, fg="white", bg="#333333")
round_btn.pack(side=LEFT, expand=TRUE, fill=BOTH)
ln_btn = Button(btnrow3, text="ln", font="Segoe 18", relief=GROOVE, bd=0, command=ln_clicked, fg="white", bg="#333333")
ln_btn.pack(side=LEFT, expand=TRUE, fill=BOTH)
sqr_btn = Button(btnrow3, text=" √x ", font="Segoe 18", relief=GROOVE, bd=0, command=sqr_clicked, fg="white", bg="#333333")
sqr_btn.pack(side=LEFT, expand=TRUE, fill=BOTH)
pow_btn = Button(btnrow3, text="x^y", font="Segoe 17", relief=GROOVE, bd=0, command=pow_clicked, fg="white", bg="#333333")
pow_btn.pack(side=LEFT, expand=TRUE, fill=BOTH)
btn7 = Button(btnrow3, text="7", font="Segoe 23", relief=GROOVE, bd=0, command=btn7_clicked, fg="white", bg="#333333")
btn7.pack(side=LEFT, expand=TRUE, fill=BOTH)
btn8 = Button(btnrow3, text="8", font="Segoe 23", relief=GROOVE, bd=0, command=btn8_clicked, fg="white", bg="#333333")
btn8.pack(side=LEFT, expand=TRUE, fill=BOTH)
btn9 = Button(btnrow3, text="9", font="Segoe 23", relief=GROOVE, bd=0, command=btn9_clicked, fg="white", bg="#333333")
btn9.pack(side=LEFT, expand=TRUE, fill=BOTH)
btnml = Button(btnrow3, text="*", font="Segoe 23", relief=GROOVE, bd=0, command=btnml_clicked, fg="white", bg="#333333")
btnml.pack(side=LEFT, expand=TRUE, fill=BOTH)
# Row 4 Buttons
btnrow4 = Frame(root)
btnrow4.pack(expand=TRUE, fill=BOTH)
dat_btn_4 = Button(btnrow4, text="dat", font="Segoe 18", relief=GROOVE, bd=0, command=dat_clicked, fg="white", bg="#333333")
dat_btn_4.pack(side=LEFT, expand=TRUE, fill=BOTH)
sinh_btn = Button(btnrow4, text="sin−1", font="Segoe 11 bold", relief=GROOVE, bd=0, command=arcsin_clicked, fg="white", bg="#333333")
sinh_btn.pack(side=LEFT, expand=TRUE, fill=BOTH)
cosh_btn = Button(btnrow4, text="cos-1", font="Segoe 11 bold", relief=GROOVE, bd=0, command=arccos_clicked, fg="white", bg="#333333")
cosh_btn.pack(side=LEFT, expand=TRUE, fill=BOTH)
dot_btn = Button(btnrow4, text=" • ", font="Segoe 21", relief=GROOVE, bd=0, command=dot_clicked, fg="white", bg="#333333")
dot_btn.pack(side=LEFT, expand=TRUE, fill=BOTH)
btnc = Button(btnrow4, text="C", font="Segoe 23", relief=GROOVE, bd=0, command=btnc_clicked, fg="white", bg="#333333")
btnc.pack(side=LEFT, expand=TRUE, fill=BOTH)
del_btn = Button(btnrow4, text="⌫", font="Segoe 20", relief=GROOVE, bd=0, command=del_clicked, fg="white", bg="#333333")
del_btn.pack(side=LEFT, expand=TRUE, fill=BOTH)
btn0 = Button(btnrow4, text="0", font="Segoe 23", relief=GROOVE, bd=0, command=btn0_clicked, fg="white", bg="#333333")
btn0.pack(side=LEFT, expand=TRUE, fill=BOTH)
btneq = Button(btnrow4, text="=", font="Segoe 23", relief=GROOVE, bd=0, command=btneq_clicked, fg="white", bg="#FA8072")
btneq.pack(side=LEFT, expand=TRUE, fill=BOTH)
btnd = Button(btnrow4, text="/", font="Segoe 23", relief=GROOVE, bd=0, command=btnd_clicked, fg="white", bg="#333333")
btnd.pack(side=LEFT, expand=TRUE, fill=BOTH)
root.mainloop()

我希望它打印出例如“BIN 111 DEC”并给我 111 的十进制数。

python binary hex decimal calculator
1个回答
0
投票

请按照以下步骤操作:

  1. 创建一个变量来存储当前输入值,初始化为空字符串。

  2. 创建一个变量来存储当前的数制(例如“BIN”、“DEC”等),初始化为None。

  3. 当点击数字转换按钮(例如“BIN”、“DEC”)时,相应地更新当前的数字系统变量。

  4. 当点击数字按钮(0-9)时,将点击的数字追加到当前输入值变量中。

  5. 点击等于按钮时,根据当前数制进行数字转换。

  6. 如果当前数制为“BIN”,则将输入值从二进制转换为十进制。

  7. 如果当前数制为“DEC”,则将输入值从十进制转换为二进制。

  8. 使用转换后的值更新显示。

    当前输入=“” 当前_编号_系统 = 无

def handle_number_conversion(number_system): 全局当前号码系统 当前系统编号 = 系统编号 # 更新显示或执行任何必要的操作

def handle_number_click(number): 全局电流输入 当前输入 += str(数字) # 更新显示或执行任何必要的操作

defhandle_equal_click(): 全局当前输入、当前数字系统 如果当前编号系统==“BIN”: 小数值 = int(当前输入, 2) 打印(“BIN”,当前输入,“DEC”,十进制值) # 更新显示或执行任何必要的操作 elif current_number_system == "DEC": 二进制值 = bin(int(当前输入))[2:] 打印(“DEC”,当前输入,“BIN”,二进制值) # 更新显示或执行任何必要的操作

使用示例

handle_number_conversion("BIN") # 用户点击BIN按钮 handle_number_click(1) # 用户点击数字1 handle_number_click(1) # 用户点击数字1 handle_number_click(1) # 用户点击数字1 handle_number_conversion("DEC") # 用户点击DEC按钮 handle_equal_click() # 用户点击等于按钮

© www.soinside.com 2019 - 2024. All rights reserved.