如何在tkinter的画布上添加标签小部件?

时间:2018-12-17 09:51:48

标签: python tkinter

所以我有这段代码可以从数据库中提取新值,并继续在应用程序上进行更新。问题是我需要以某种吸引人的方式显示这些值,而我需要画布,但我无法这样做。 画布无法正常工作。它不会在应用程序上做任何形状。我确定我犯了一个错误,但我不知道是什么。帮我谢谢。

代码:

data Numeric = N Double
   deriving Show

instance Num Numeric where
   (*) (N a) (N b) = N (a * b) 
   (+) (N a) (N b) = N (a + b) 
   (-) (N a) (N b) = N (a - b) 
   abs (N a) = N $ abs a
   signum (N a) = N $ signum a
   fromInteger a = N $ fromInteger a

instance Fractional Numeric where
   fromRational d = N $ fromRational d
   (/) (N a) (N b) = N (a / b) 

1 个答案:

答案 0 :(得分:0)

实际上您的代码正在运行,但是canvas覆盖了lbl_cod_data,因此您看不到它。尝试将所有.grid(...)更改为.place(...),如下所示:

canvas.place(x=0, y=0)
lbl_cod_data.place(x=50, y=100)
lbl_bod_data.place(x=50, y=200)
lbl_tss_data.place(x=50, y=300)

然后您可以同时看到标签和画布。

但是,在画布上使用标签小部件并不是一个好的设计(例如,标签小部件不能具有透明背景)。

建议改用画布文本。下面是一个基于您的修改后的代码作为示例:

import Tkinter as tk
import sqlite3
from constants import DELAY,DB_PATH

def update_data_for_cod_bod():
    conn = sqlite3.connect('ubiqx_db.db')
    c = conn.cursor()
    execute_query = c.execute('''select cod,bod,tss from front_end_data where slave_id=1''')
    result_set = c.fetchall()

    data_for_cod = 0
    data_for_bod = 0
    data_for_tss = 0
    for row in result_set:
        data_for_cod = row[0] # do you actually want += instead?
        data_for_bod = row[1]
        data_for_tss = row[2]
    # use itemconfig() to modify the labels text
    canvas.itemconfig(lbl_cod_data, text="COD             "+str(data_for_cod))
    canvas.itemconfig(lbl_bod_data, text="BOD             "+str(data_for_bod))
    canvas.itemconfig(lbl_tss_data, text="TSS             "+str(data_for_tss))
    root.after(DELAY, update_data_for_cod_bod)  # Call this function again after DELAY ms.

root = tk.Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.overrideredirect(1)
root.geometry("%dx%d+0+0" % (w, h)) # (h, w) in your original code
root.title("COD_BOD")
root.configure(background='black')
root.bind("<Escape>", lambda e: root.quit())

# width=h and height=w in your original code
canvas = tk.Canvas(root, width=w, height=h, highlightthickness=0, bg="dark blue")
canvas.pack()

blackline = canvas.create_line(100, 100, 800, 100, fill="yellow")

lbl_font = ("Times New Roman", 50, "bold")
lbl_cod_data = canvas.create_text(100, 100, text="COD", font=lbl_font, anchor='nw', fill="white")
lbl_bod_data = canvas.create_text(100, 180, text="BOD", font=lbl_font, anchor='nw', fill="green")
lbl_tss_data = canvas.create_text(100, 260, text="TSS", font=lbl_font, anchor='nw', fill="yellow")

update_data_for_cod_bod()  # Starts periodic calling of itself.
root.mainloop()