我无法使用tview更新文本。

huangapple go评论78阅读模式
英文:

I cannot update text with tview

问题

我正在使用Go语言中的tview

我想使用以下代码在终端上显示"hoge",但它没有显示出来。

package main

import (
	"fmt"

	"github.com/rivo/tview"
)

func main() {
	tui := newTui()
	tui.Run()
	tui.WriteMessage("hoge")
}

type Tui struct {
	app  *tview.Application
	text *tview.TextView
}

func (t *Tui) Run() {
	t.app.Run()
}

func (t *Tui) WriteMessage(message string) {
	fmt.Fprintln(t.text, message)
}

func newTui() *Tui {
	text := tview.NewTextView()

	app := tview.NewApplication()
	app.SetRoot(text, true)

	text.SetChangedFunc(func() { app.Draw() })

	tui := &Tui{app: app, text: text}

	return tui
}

我不想在newTui()函数中更新文本。

如何使其显示出来?

英文:

I'm using tview in the Go language.

I want to use the following code to display "hoge" on the terminal, but it does not show up.

package main

import (
	"fmt"

	"github.com/rivo/tview"
)

func main() {
	tui := newTui()
	tui.Run()
	tui.WriteMessage("hoge")
}

type Tui struct {
	app  *tview.Application
	text *tview.TextView
}

func (t *Tui) Run() {
	t.app.Run()
}

func (t *Tui) WriteMessage(message string) {
	fmt.Fprintln(t.text, message)
}

func newTui() *Tui {
	text := tview.NewTextView()

	app := tview.NewApplication()
	app.SetRoot(text, true)

	text.SetChangedFunc(func() { app.Draw() })

	tui := &Tui{app: app, text: text}

	return tui
}

I don't want to update the text in the newTui() function.

How do I get it to show up?

答案1

得分: 1

func (*Application) Run()

> Run 启动应用程序,从而启动事件循环。只有在调用 Stop() 后,此函数才会返回。

也就是说,在你的程序中,语句 tui.WriteMessage("hoge") 永远不会被执行,因为 Run() 直到显式停止才会返回。所以,为了在终端中看到 "hoge" 被打印出来,你必须在 Run() 之前调用 tui.WriteMessage("hoge")

func main() {
	tui := newTui()
	tui.WriteMessage("hoge")
	tui.Run()
}
英文:

func (*Application) Run():

> Run starts the application and thus the event loop. This function
> returns when Stop() was called.

i.e. The statement tui.WriteMessage("hoge") in your program is never reached because Run() doesn't return until stopped explicitly. So to see hoge printed in the terminal, you must call tui.WriteMessage("hoge") before Run().

func main() {
	tui := newTui()
	tui.WriteMessage("hoge")
	tui.Run()
}

huangapple
  • 本文由 发表于 2022年1月12日 23:41:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/70684393.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定